基本上,我正在制作一个caesar密码程序,用于加密或解密用户输入的消息。但是,如果用户在消息中输入空格(例如Stack Overflow),它将对空格和字母执行加密或解密偏移处理,显然我不希望它这样做。我希望它忽略空格并在加密或解密的消息中打印它们。
这是我的代码:
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;
答案 0 :(得分:1)
for(int p = 0 ; p < 105; p++) {
if (plaintext[p] == ' ') continue;
您需要保持空间不受影响,同时从chars
数组
答案 1 :(得分:0)
你的程序中有一些逻辑问题,你的程序的第一个问题是,没有空格检查'',因此程序不知道在找到空格时该做什么,其次你要添加{{ 1}}所以无论它在文本中找到什么,它都会将其添加到palinttext[c]=chars[p+offset]
,包括空格''。因此,要解决此问题,您需要在代码中添加空格'',以避免空间需要添加另一个字符串(palintext[p]
)来存储所需的输出,我向您显示修改后的代码:
output