我有一個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循環中。我不知道這裏發生了什麼事。
由於這個'Integer.parseInt',你得到了錯誤。你期望int。 –
你卡住了什麼?你確定它不只是在等待你的下一個輸入? – Shiping
你在每次迭代中調用'guess()'兩次,一次在條件檢查中,另一次在循環體中調用。東西告訴我,你正在尋找:[如何使用掃描儀接受只有有效的int作爲輸入](http://stackoverflow.com/questions/2912817/how-to-use-scanner-to-accept-only-valid -int-as-input) – Pshemo