如何在 Java 中创建密码

How to create a cipher in Java

我目前正在创建代码以使用预定义字符对 Java 中的文本进行加密。该代码正在运行,除了我不知道如何在我的代码中处理 spaces。当程序到达 space 时,它似乎终止了,但我希望它能够读入并加密完整的句子。很抱歉解释不当,但希望代码能说明我遇到的问题。

public static final int ASCII_SUB = 96;
public static final int ASCII_SUB_FOR_SPACE = 32;

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("Enter the text that you would like to cipher:");
    Scanner input = new Scanner(System.in);
    String cipher = input.next();
    input.close();

    int length = cipher.length();

    char encryption[] = createCipher();
    String encrypted = encrypt(encryption, cipher, length);

    System.out.println(encrypted);


}

public static char[] createCipher(){

    char[] encryption = {'p', 'u', 'y', 'k', 'h', 'q', 'g', 'j', 'l',
            'i', 'd', 'v', 'b', ' ', 'o', 'c', 'f', 'r', 'e', 't', 'x',
            'a', 'n', 'z', 'm', 'g', 'w', 's' };

    return encryption;
}

public static String encrypt(char[] encryption, String cipher, int length){

    String lowercaseCipher = cipher.toLowerCase();
    char[] characterArray = lowercaseCipher.toCharArray();

    char[] test = new char[length];
    for(int i = 0; i<length; i++){
        if(characterArray[i] == ' '){
            test[i] = (char) (characterArray[i] - ASCII_SUB_FOR_SPACE);
        }
        else{
            test[i] = (char) (characterArray[i] - ASCII_SUB);
        }

    char test2[] = new char[length];

    for(int i = 0; i<length; i++){
        test2[i] = encryption[test[i]];
    }

    String anotherString = new String( test2 );
    return anotherString;
}

当我输入类似 "ab aq" 的内容时。

程序打印出"uy"

提前致谢

不使用 input.next(),它将输入 读取到下一个白色 space 字符 ,而是使用 input.nextLine()。这将为您提供完整的行(当然没有行尾字符)。