Console.readPassword() 在 java 中创建无限循环

Console.readPassword() creates infinite loop in java

我正在通过控制台开发银行程序。我想在用户输入密码时隐藏它。

我创建了自己的方法,该方法使用控制台中的 readPassword() 方法读取密码和 returns 字符串 class:

/**
 * Reads Password without allowing the console to show the characters 
    while the user is typing the password.
 * @return
 */
public String readPass(){
    String pass = "";
    Console cnsl = System.console();
    if(cnsl!=null){
        char[] pword = cnsl.readPassword();
        for(char c: pword){
            pass+=c;
        }
        return pass;
    }
    return "";
}

该方法是从另一个调用的 class:

/**
 * Asks the user to enter their password. Then checks if the password is right.
 * @param u
 */
public void checkPassword(User u){
    boolean pa = false;
    do{
        System.out.print("Please enter your password: ");
        //String pword = in.next();
        String pword = b.readPass();
        pa = u.checkPassword(pword);
        if(pa){
            System.out.println("\nLogin Successful...");
            System.out.println("\nWelcome "+ u.getName() + "!");
            enterAccount(u);
        }
        else{
            System.out.println("That is the incorrect password. Please try again.\n");
        }
    }while(!pa);
}

提示输入密码的那一刻,执行else块,结果死循环。

如果您的控制台为空,则无限循环可以 occur.There 是 eclipse 中的 bug,这会导致 System.console.

的 npe

尝试使用 Scanner 来测试代码。

请阅读本文explanation

From console java doc 虚拟机是否有控制台取决于底层平台以及调用虚拟机的方式。如果虚拟机是从交互式命令行启动的,而没有重定向标准输入和输出流,那么它的控制台将存在,并且通常会连接到启动虚拟机的键盘和显示器。如果虚拟机是自动启动的,例如通过后台作业调度程序,那么它通常没有控制台。

此外,您可以将字符数组转换为字符串,而不是重复连接字符,如 pass = new String(pword)

如果您想从 IDE 进行测试,请尝试使用扫描仪(输入密码时会看到密码)或者您可以创建一个小的 JDialog 并在其中嵌入一个 JPasswordField