gpt4 book ai didi

java - 移位密码错误地移位了一些字符

转载 作者:行者123 更新时间:2023-12-02 11:34:04 25 4
gpt4 key购买 nike

我正在尝试使用移位密码来解码消息。我的一些角色翻译得很好,但其他的则不然。我无法弄清楚问题是什么。

public class ShiftCipher {

public static void main(String[] args) {

System.out.println(cipher("F30MDAAFEMA1MI0EF0D9", 14));
}

static String cipher(String msg, int shift){
String characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
String DecryptedMessege = "";
String DecryptedChar = "";
int trueShift;
boolean in = false; //Debugging
for(int x = 0; x < msg.length(); x++){
for (int y = 0; y < characters.length(); y++ ) {
if (msg.charAt(x) == characters.charAt(y)){
if (y+shift <= characters.length()){
trueShift = y + shift;
in = true; //Debugging
}
else {
trueShift = shift - (characters.length() - y);
in = false; //Debugging
}

DecryptedChar = new StringBuilder().append(characters.charAt(trueShift)).toString();
System.out.println(DecryptedChar + " " + in + " " + trueShift); //Debugging
}
}
DecryptedMessege = DecryptedMessege + DecryptedChar;
}
return DecryptedMessege;
}
}

一些早期字母被错误地移至 -1。输出应为“THE ROOTS OF WESTERN”,但改为“TGD ROOTS OE WDSTDRN”。

有人知道为什么这不起作用吗?欢迎任何意见。

最佳答案

使用模 %(整数除法的余数):模 4 会计算 0, 1, 2, 3, 0, 1, 2, 3, ...

下面的内容比 if-then-else 更容易。

          trueShift = (y + shift) % characters.length();

或者如果 y+shift 可能为负(那么 trueShift 也会变为负),更好:

          int n = characters.length();
trueShift = (y + shift + n) % n;

在您的其他部分 trueShift 不是对称的(单射,不是双射):decrypt(encrypt(s)) != s。如果 0,1,2,3 映射到 0,1,1,0 就会出现问题。

<小时/>
static String cipher(String msg, int shift){
String characters = "01234556789ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
int n = characters.length();
StringBuilder decryptedMessage = new StringBuilder();
for (int x = 0; x < msg.length(); x++) {
char ch = msg.charAt(x);
int y = characters.indexOf(ch);
if (y != -1) {
int trueShift = (y + shift + n) % n;
ch = characters.charAt(trueShift);
}
decryptedMessage.append(ch);
}
return decryptedMessage.toString();
}

关于java - 移位密码错误地移位了一些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49081138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com