【问题标题】:Caesar Cipher not reading words after a space, cannot figure out whyCaesar Cipher 在空格后不读取单词,无法弄清楚原因
【发布时间】:2019-04-04 03:45:16
【问题描述】:

我需要为作业编写一个简单的凯撒密码,并且我必须使用左移 3 来加密消息“这是凯撒密码”。我尝试使用 IF 语句,后跟“继续;”但它不起作用,我一生都无法弄清楚是什么导致了这个问题哈哈。

public static String encrypt(String plainText, int shiftKey) {
    plainText = plainText.toLowerCase();
    String cipherText = "";
    for (int i = 0; i < plainText.length(); i++) {
    char replaceVal = plainText.charAt(i);
    int charPosition = ALPHABET.indexOf(replaceVal);        
    if(charPosition != -1) {
        int keyVal = (shiftKey + charPosition) % 26;
        replaceVal = ALPHABET.charAt(keyVal);
    }

    cipherText += replaceVal;
    }
    return cipherText;
}
public static void main (String[] args) {
    String message;
    try (Scanner sc = new Scanner(System.in)) {
        System.out.println("Enter a sentence to be encrypted");
        message = new String();
        message = sc.next();
    }
 System.out.println("The encrypted message is");
 System.out.println(encrypt(message, 23));
}

}

【问题讨论】:

  • 解释如何它不起作用。你有例外吗?结果不符合你的预期吗?
  • 比如说我将输入“这是一个凯撒密码”,输出消息是“qefp”。我设法完成了 3 的左移,但是如果我输入“thisisacaesarcipher”,输出消息是“qefpfpxzxbpxozfmebo”,我无法理解如何过滤掉空格来加密句子,而不是单个字符串

标签: java spaces caesar-cipher


【解决方案1】:

您只使用Scanner.next() 阅读一个单词并且从不使用new String()。改变

message = new String();
message = sc.next();

message = sc.nextLine();

还值得注意的是 StringBuilder 和简单的算术是凯撒密码所需要的。例如,

public static String encrypt(String plainText, int shiftKey) {
    StringBuilder sb = new StringBuilder(plainText);
    for (int i = 0; i < sb.length(); i++) {
        char ch = sb.charAt(i);
        if (!Character.isWhitespace(ch)) {
            sb.setCharAt(i, (char) (ch + shiftKey));
        }
    }
    return sb.toString();
}

public static void main(String[] args) {
    int key = 10;
    String enc = encrypt("Secret Messages Are Fun!", key);
    System.out.println(enc);
    System.out.println(encrypt(enc, -key));
}

哪些输出

]om|o~ Wo}}kqo} K|o Px+
Secret Messages Are Fun!

【讨论】:

  • 这个答案对您有帮助吗?考虑接受它以表达你的感激之情。
猜你喜欢
  • 2022-07-17
  • 1970-01-01
  • 1970-01-01
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
相关资源
最近更新 更多