【发布时间】:2015-09-27 05:54:13
【问题描述】:
我正在为我的计算机科学课程简介制作凯撒密码,但我被卡住了。我已经想出了如何满足项目所需的一些元素,如空格,并且当加密密钥设置为固定数字时,我让它工作。但是,其中一个要求是当您点击“z”时字母会环绕,并且用户可以输入他们自己的加密密钥值。它还需要加密和解密消息。 任何人都可以给我关于我哪里出错的任何提示将不胜感激! 到目前为止,这是我所拥有的:(我是在 Eclipse 中制作的)
import java.util.Scanner;
public class CaesarCipher {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the message? (all lowercase)");
String plainText = keyboard.nextLine();
System.out.println("Please enter the encryption key: ");
int encryptionKey = keyboard.nextInt();
System.out.println("The encrypted text is: ");
int charPos = 0;
while (charPos < plainText.length()) {
char currChar = plainText.charAt(charPos);
int charAsNum = (int) currChar;
int cipherLetterAsNum = charAsNum + encryptionKey;
char cipherLetter = (char) cipherLetterAsNum;
if (currChar == 'x' || currChar == 'y' || currChar == 'z') {
currChar = plainText.charAt(charPos);
charAsNum = (int) currChar;
cipherLetterAsNum = charAsNum + encryptionKey - 26;
cipherLetter = (char) cipherLetterAsNum;
System.out.print(cipherLetter);
charPos = charPos + 1;
}
if (currChar == ' ') {
System.out.print(currChar);
} else {
System.out.print(cipherLetter);
}
charPos = charPos + 1;
}
}
}
【问题讨论】:
-
a) 使用输入字符来决定是否需要更改。 b)
<运算符来决定,如果你需要减去 26。或者你可以使用%运算符:cOut = (cIn - 'a' + encryptionKey) % 26 + 'a'
标签: java encryption caesar-cipher