兩件事情:
首先,也是最重要的,你必須與下一行的輸入賦給變量pass
。
String pass = ...;
...
pass = input.nextLine();
其次,你應該與equals
做字符串比較。參考比較!=
(或==
)可能有效,但不能保證。所以雖然條件應該是:
while(!"sesame".equals(pass)){ ...
運營商!=
和==
的對象引用操作,有利於比較對象的身份。對於字符串,它們可能會工作,因爲JVM在字符串上爲某些字符串使用相同的實例。因此,有沒有保證,
例如:
"bla" != new String("bla")
因此字符串應該與equals
進行比較。另外,如果與之比較的字符串是已知的(如在"sesame"
中),建議首先將其放在第一位,因爲它永遠不可能是null
,這可能是變量的情況。
例如:
"sesame".equals(pass)
不會拋出一個NullPointerException
即使pass
是null
所以最後你main
應該像最終
public static void main(String[] args) {
String pass = "thing";
while(!"sesame".equals(pass)){ //comparison with equals
System.out.println("The correct password is sesame. Please enter that.");
Scanner input = new Scanner(System.in);
pass = input.nextLine(); //assign result to pass
}
一個說明,有Console作爲通行證,更適合讀密碼的班級詞不是打印出來給終端:
Console cons = System.console();
char[] passwd = cons.readPassword("[%s]", "Password:"));
但是記住,那System.console()
可能返回null,如果你在你的IDE使用亞軍運行你的代碼,這可能發生。
我試着分配傳球input.next線,但我只是得到一個重複的局部變量的錯誤。 – TPG
不要'String pass = input.nextLine()',只是'pass = input.nextLine()' –
謝謝,修復了它。 – TPG