凯撒密码后不读文字的空间,无法弄清楚为什么

问题描述 投票:0回答:1

我需要为一个赋值编写一个简单的Caesar密码,我必须加密消息“This is a Caesar cipher”,左移为3.我尝试使用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));
}

}

java spaces caesar-cipher
1个回答
0
投票

你只用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!
© www.soinside.com 2019 - 2024. All rights reserved.