1

我到处寻找,似乎找不到空间的转义序列。我目前正在使用“”作为空间,但它不起作用。我的散列函数需要它,当它散列包含空格字符的密码时,它无法正确计算。

例如,当我在我的程序中输入“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);

    }

}
4

3 回答 3

4

当你构造你的 Scanner 对象时,传入分隔符,"\\n"以便它扫描整行。

就像是: new Scanner(System.in).useDelimiter("\\n");

于 2013-01-08T23:35:30.227 回答
3

只是改变

String password = scan.next();

String password = scan.nextLine();
于 2013-01-08T23:38:35.073 回答
1

  String password = scan.next();

只读取第一个单词。http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String )

将分隔符设置为换行符\n

于 2013-01-08T23:35:37.667 回答