2017-04-26 185 views
-2

我有一個boolean Guess功能:do while循環錯誤,卡在while循環

public boolean guess() { 
    String checkInput = scanner.nextLine(); 

    try { 
    guess = Integer.parseInt(checkInput); 
    } catch (NumberFormatException e) { 
    return false; 
    } 

    return true; 
} 

這是在做另一個函數調用while循環:如果我進入int

while (!player.guess()) { 
    player.guess(); 
} 

,該程序正常運行並終止。但是如果輸入是一個非int字符,程序會卡在while循環中。我不知道這裏發生了什麼事。

+0

由於這個'Integer.parseInt',你得到了錯誤。你期望int。 –

+0

你卡住了什麼?你確定它不只是在等待你的下一個輸入? – Shiping

+0

你在每次迭代中調用'guess()'兩次,一次在條件檢查中,另一次在循環體中調用。東西告訴我,你正在尋找:[如何使用掃描儀接受只有有效的int作爲輸入](http://stackoverflow.com/questions/2912817/how-to-use-scanner-to-accept-only-valid -int-as-input) – Pshemo

回答

0

你猜功能就是這樣設計的。 如果輸入不是數字(catch),則返回false。所以它一直保持在循環中,直到你輸入一個數字值。 另一個問題是你每次循環調用兩次函數(一次在循環條件檢查,另一次在循環內部)。所以如果你在第一個(循環條件)和第二個(在循環內)鍵入一個非數字字符,它仍然會要求第三次輸入。

我不知道你的意圖是什麼,但你可能會想是這樣的:

while (!player.guess()) { 
    continue; 
} 

除非你真的想要它被稱爲兩次。

+0

這很有道理。但我不知道如何將其編碼到解決方案中。 – grammerPro

+0

該解決方案解決了我的問題。該程序只提示一次int輸入,然後退出。我以前不知道如何使用這個構造和'continue'。謝謝! – grammerPro

0

您的scanner.nextLine()永遠讀取該行,它不會要求另一個輸入。

0
while (!player.guess()) { // Entered Integer. (!true) and loop breaks 
    player.guess(); 
} 

while (!player.guess()) { // Entered Non-Integer. (!false) and program enters the loop 
    player.guess(); // You are not storing the result in some boolean variable 
    //Therefore, it doesn't matter whether true or false 
    //while (!player.guess()) will be checked once again 
} 

SOLUTION:

boolean flag = player.guess(); // capture the result 
    while (!flag) { // verify the result 
     flag = player.guess(); // capture the result again 
    } 
+0

沒有必要檢查這裏的其他例外。 –

+0

感謝您的嘗試,但這並未解決我的問題。 – grammerPro

+0

@grammerPro,我已經更新了代碼與評論中的信息:) 請看看。 –