0

我正在为计算机科学课程的介绍制作凯撒密码,但我被卡住了。我已经想出了如何满足项目所需的一些元素,如空格,并且当加密密钥设置为固定数字时,我让它工作。但是,其中一项要求是当您点击“z”时字母会环绕,并且用户可以输入他们自己的加密密钥值。它还需要加密和解密消息。任何人都可以给我关于我哪里出错的任何提示将不胜感激!这是我到目前为止所拥有的:(我是在 Eclipse 中制作的)

import java.util.Scanner;

public class CaesarCipher {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("What is the message? (all lowercase)");
        String plainText = keyboard.nextLine();

        System.out.println("Please enter the encryption key: ");
        int encryptionKey = keyboard.nextInt();

        System.out.println("The encrypted text is: ");
        int charPos = 0;

        while (charPos < plainText.length()) {
            char currChar = plainText.charAt(charPos);
            int charAsNum = (int) currChar;
            int cipherLetterAsNum = charAsNum + encryptionKey;
            char cipherLetter = (char) cipherLetterAsNum;

            if (currChar == 'x' || currChar == 'y' || currChar == 'z') {
                currChar = plainText.charAt(charPos);
                charAsNum = (int) currChar;
                cipherLetterAsNum = charAsNum + encryptionKey - 26;
                cipherLetter = (char) cipherLetterAsNum;
                System.out.print(cipherLetter);
                charPos = charPos + 1;
            }

            if (currChar == ' ') {
                System.out.print(currChar);
            } else {
                System.out.print(cipherLetter);
            }
            charPos = charPos + 1;
        }
    }
}
4

1 回答 1

0

我认为您必须检查 encryptedChar 是否大于 91(z 的 ascii 值),如果是,则应减去 26。如果要解密文本,只需减去 encryptionKey,如果 encryptedChar小于65(a的ascii值),要加26。我不确定ascii值是否正确,最好查一下。

于 2015-09-26T21:54:13.113 回答