【发布时间】:2019-04-04 03:45:16
【问题描述】:
我需要为作业编写一个简单的凯撒密码,并且我必须使用左移 3 来加密消息“这是凯撒密码”。我尝试使用 IF 语句,后跟“继续;”但它不起作用,我一生都无法弄清楚是什么导致了这个问题哈哈。
public static String encrypt(String plainText, int shiftKey) {
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++) {
char replaceVal = plainText.charAt(i);
int charPosition = ALPHABET.indexOf(replaceVal);
if(charPosition != -1) {
int keyVal = (shiftKey + charPosition) % 26;
replaceVal = ALPHABET.charAt(keyVal);
}
cipherText += replaceVal;
}
return cipherText;
}
public static void main (String[] args) {
String message;
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter a sentence to be encrypted");
message = new String();
message = sc.next();
}
System.out.println("The encrypted message is");
System.out.println(encrypt(message, 23));
}
}
【问题讨论】:
-
解释如何它不起作用。你有例外吗?结果不符合你的预期吗?
-
比如说我将输入“这是一个凯撒密码”,输出消息是“qefp”。我设法完成了 3 的左移,但是如果我输入“thisisacaesarcipher”,输出消息是“qefpfpxzxbpxozfmebo”,我无法理解如何过滤掉空格来加密句子,而不是单个字符串
标签: java spaces caesar-cipher