我正在制作一个Caesar密码,用于我的计算机科学课程介绍,我被卡住了。我已经想出如何满足项目的一些必需元素,如空格,并且当加密密钥设置为固定数字时,我已将其工作。但是,其中一个要求是,当您点击“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;
}
}
}
答案 0 :(得分:0)
我认为你必须检查encryptedChar是否大于91(z的ascii值),如果是,它应该减去26。如果你想解密文本,你只需要减去encryptionKey和如果encryptedChar小于65(ascii值为a),则必须添加26.我不确定ascii值是否正确,因此请更好地查找。