0
我爲我的計算機科學課程介紹製作凱撒密碼,並且卡住了。我已經想出瞭如何滿足像空間這樣的項目所需的一些元素,並且我已經在加密密鑰設置爲固定數字時工作。但是,其中一個要求是,當您點擊「z」時,字母表會環繞並且用戶可以輸入自己的加密密鑰值。還需要加密和解密消息。 任何提示任何人都可以給我我要去哪裏錯將不勝感激! 這是我到目前爲止有:(我是做這在Eclipse)在Java中製作凱撒密碼
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'' – fabian