基本上,我正在制作一个凯撒密码程序,用于加密或解密用户输入的消息。但是,如果用户在消息中输入空格(例如堆栈溢出),它将对空格和字母执行加密或解密偏移过程,显然我不希望它这样做。我希望它忽略空格并将它们打印在加密或解密的消息中。
这是我的代码:
Scanner myinput = new Scanner(System.in);
String plain;
String encrypted;
char chars[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', ' ', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', ' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', ' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', ' '};
System.out.println("Please enter your message.");
plain = myinput.nextLine().toUpperCase();
myinput.close();
char[] plaintext = plain.toCharArray();
if(plain.isEmpty()) {
System.out.println("You need to give me a message to encrypt.");
}
for(int c = 0;c < plaintext.length;c++) {
for(int p = 0 ; p < 105;p++) {
if(p <= 100) {
if(plaintext[c] == chars[p]) {
plaintext[c] = chars[p + offset];
break;
}
}
else if(plaintext[c] == chars[p]) {
plaintext[c] = chars[p - 81];
}
}
}
encrypted = String.valueOf(plaintext);
return encrypted;