凯撒密码(Caesar Cipher)在空格后不阅读单词,无法弄清楚

时间:2019-04-04 03:45:16

标签: java spaces caesar-cipher

我需要为分配编写一个简单的Caesar密码,并且必须向左移动3来加密消息“ This is Caesar cipher”。我尝试使用IF语句后跟“ continue;”。但是它不起作用,我无法一生找出导致此问题的原因哈哈。

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));
}

}

1 个答案:

答案 0 :(得分:0)

您仅使用Scanner.next()读一个单词,并且从不使用new String()。更改

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

message = sc.nextLine();

值得注意的是,StringBuilder和简单的算术是您使用Caesar Cipher所需要的。例如,

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!