我目前正在创建代码以使用预定义字符在 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/