我到处寻找,我似乎无法找到空间的转义序列。我目前正在使用“”用于空间,但它不起作用。我需要它用于我的哈希函数,当它散列包含空格字符的密码时无法正确计算。
例如,当我在程序中输入“aaa aaa”时,它会输出“>& q”。我的函数应该根据密码输出一个七字符哈希值,但它会在空格处停止,只留下三个字符的输出。但是,在给定某些输入的情况下,该函数仍可输出空间。
import java.util.*;
public class Hasher {
private static Scanner scan;
/*
* This function will generate a hash based off a password entered by the
* user
*/
public static void main(String[] args) {
scan = new Scanner(System.in);
System.out.println("What is your password?");
String password = scan.next();
String characters = "qwertyuiopasdfghjklzxcvbnm";
characters = characters + characters.toUpperCase();
characters = characters + "1234567890";
characters = characters + " ";
characters = characters + "!@#$%^&*()_+-=`~\b[]?-{};',./:\"<>?\\";
char[] array = new char[2 * characters.length()];
for (int y = 0; y < array.length; y++) {
Random rand = new Random(y);
array[y] = characters.charAt(rand.nextInt(characters.length()));
}
String newPass = "";
for (int y = 0; y < password.length(); y++) {
char x = password.charAt(y);
for (int z = 0; z < characters.length(); z++) {
if (x == characters.charAt(z)) {
Random rand = new Random(y);
x = array[z + rand.nextInt(array.length - z)];
newPass = newPass + x;
break;
}
}
}
System.out.println("Your hash is: " + newPass);
}
}
答案 0 :(得分:4)
构建Scanner对象时,将分隔符作为"\\n"
传递,以便扫描整行。
类似于:new Scanner(System.in).useDelimiter("\\n");
答案 1 :(得分:3)
只需更改
String password = scan.next();
到
String password = scan.nextLine();
答案 2 :(得分:1)
此
String password = scan.next();
只读第一个单词。 http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)
将分隔符设置为新行\n
字符。