繁体   English   中英

如何在Java中创建密码

[英]How to create a cipher in Java

我目前正在创建使用预定义字符在Java中加密文本的代码。 代码正在运行,除了我不知道如何在我的代码中处理空格。 当程序到达一个空间时它似乎终止但我希望它能够读入和加密完整的句子。 对于糟糕的解释表示歉意,但希望代码能够显示我遇到的问题。

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”的东西时。

该程序打印出“你”

提前致谢

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM