我正在为计算机科学课程的介绍制作凯撒密码,但我被卡住了。我已经想出了如何满足项目所需的一些元素,如空格,并且当加密密钥设置为固定数字时,我让它工作。但是,其中一项要求是当您点击“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;
}
}
}