java - 如何在 Java 中创建密码

标签 java ascii

我目前正在创建代码以使用预定义字符在 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”的内容时。

程序打印出“uy”

提前致谢

最佳答案

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

关于java - 如何在 Java 中创建密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27759642/

相关文章:

java - 抽象类 - 为什么我的 protected 方法可以公开访问?

java - 将整数数组列表转换为基于ascii表的字符串并与字符串进行比较

c - putc() 在 c 中返回什么?

algorithm - 我们为什么要使用 Base64?

java - 在 Eclipse Workbench 状态行中同时写入两个消息

java - 服务类中的 Spring Autowired 异常

assembly - 显示 ascii 十六进制值数组中的一串字符汇编语言

java - TextView::getText() 对于不可见字符返回 -3

java - 创建椭圆画笔图像的算法?

java - Android 工具栏问题