我正在尝试用 Java 编写一个 Caesar cipher 解码器,但我得到了意外的输出(参见下面的示例)。
BetterDecrypt()
方法需要一个要解码的字符串 cipherText
,以及一个整数 shiftKey
,它是字符串中每个字符要在字母表中向上或向下移动的位数。如果一个字符不在String ALPHABET = "abcdefghijklmnopqrstuvwxyz"
中,那么我想保持该字符不变,例如“ab4c”应该解码为“bc4d”。
import java.io.*;
import java.util.*;
public class SimpleDecoder {
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String BetterDecrypt(String cipherText, int shiftKey) {
cipherText = cipherText.toLowerCase();
String message = "";
for (int ii = 0; ii < cipherText.length(); ii++) {
char character = cipherText.charAt(ii);
if (ALPHABET.contains(Character.toString(character))) {
int charPosition = ALPHABET.indexOf(cipherText.charAt(ii));
int keyVal = (charPosition - shiftKey) % 26;
if (keyVal < 0) {
keyVal = ALPHABET.length() + keyVal;
char replaceVal = ALPHABET.charAt(keyVal);
message += replaceVal;
}
} else {
message += character;
}
}
return message;
}
public static void main(String[] args) {
System.out.println(BetterDecrypt("ab4c", -1));
// OUTPUT: 4 EXPECTED OUTPUT: bc4d
System.out.println(BetterDecrypt("ab4c", 1));
// OUTPUT: z4 EXPECTED OUTPUT: za4b
}
}
您的
keyVal < 0
条件是包装了太多代码:
if (keyVal < 0) {
keyVal = ALPHABET.length() + keyVal;
char replaceVal = ALPHABET.charAt(keyVal);
message += replaceVal;
}
应该是
if (keyVal < 0) {
keyVal = ALPHABET.length() + keyVal;
}
char replaceVal = ALPHABET.charAt(keyVal);
message += replaceVal;
否则,您将省略所有不从 a -> z 环绕的移位字符。
如果
keyVal
大于 0,那么您就不会执行任何操作。这是最简单的修复方法
if(keyVal < 0) {
keyVal = ALPHABET.length() + keyVal;
char replaceVal = ALPHABET.charAt(keyVal);
message += replaceVal;
}
else
message += ALPHABET.charAt(keyVal);