2015-06-22 49 views
0

我通過控制檯工作的一個銀行程序無限循環。我想在用戶輸入密碼時隱藏密碼。Console.readPassword()創建Java中

我創造了我自己的方法來讀取密碼,並返回使用readPassword()方法在控制檯類的字符串:

/** 
* 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 ""; 
} 

的方法是從另一個類叫做:

/** 
* 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塊並且結果是無限循環。

+1

@AhsN內,他爲什麼要這麼做?它將作爲循環中的第一個語句執行。 – Seelenvirtuose

+1

@SpecialK也許你的方法'User.checkPassword(String)'總是返回'false'?另外,如果你沒有控制檯會發生什麼?你將不會有機會輸入任何東西,但是你的'readPass'方法只是返回一個空字符串(總是)。也許這是你的無限循環? – Seelenvirtuose

+0

你確定checkPassword正常嗎? – zubergu

回答

1

如果您的控制檯爲空,則會發生無限循環。在eclipse中有一個bug,它導致System.console的npe。

嘗試使用掃描儀進行測試代碼。

請閱讀本explanation

From console java doc 無論是虛擬機具有控制檯取決於底層平臺,也取決於在其中虛擬機被調用的方式。如果虛擬機從一個交互式命令行開始,而不需要重新定向標準輸入和輸出流,那麼其控制檯將存在並且通常將被連接到從所述虛擬機發起的鍵盤和顯示器。如果虛擬機是自動啓動的,例如通過後臺作業調度程序,那麼它通常沒有控制檯。

此外,而不是反覆concatinating字符,可以字符數組轉換成字符串作爲pass = new String(pword)

如果你想從IDE進行測試,請嘗試使用掃描儀(密碼將是可見的,打字時),或者你可以創建一個小JDialog和嵌入JPasswordField

+0

只有當OP沒有從命令提示符運行時,情況就是這樣。但是如果他從命令提示符運行,那麼可能是什麼原因? – Blip

+0

我正在使用eclipse及其控制檯,並且以前一切正常,當我使用掃描儀時,除了密碼未被隱藏。如果我無法使用System.console,如何隱藏密碼? –

+0

這是絕對的問題,因爲我在調試後意識到,但是什麼是等效的解決方法? –