0
我有一個代碼return語句DO-而
boolean playerTakesAHit() throws IOException {
char ch = ' '; boolean hit=false;
do{
System.out.print("Hit or Stay: ");
System.out.flush();
String playersDecision = keyboardInput.readLine();
try {ch = playersDecision.charAt(0);
} catch (StringIndexOutOfBoundsException exception) {
if(ch == 'H' || ch == 'h') {
return true;
}
if(ch == 'S' || ch == 's') {
return false;
}}
} while(true);
我要的是這個方法將重複而用戶打H/H(返回true),並立即停止當用戶打S/S。但是,當我把使用這種方法:
...
while(playerTakesAHit()) {
System.out.println("Player Hit");
}
...
我得到了這樣的事情:
命中還是留:H
命中還是留:H
命中還是留:■
打或留:S
命中或逗留:
它重複詢問命中或保留用戶的任何輸入。有人知道我的錯誤在哪裏嗎?
你的if語句應該是在try塊,不閉鎖段。 – PeterJ
它永遠不會擺脫你的'do ... while'循環,因爲它永遠是真的。 – squiguy
@PeterJ謝謝。 這是我的解決方案... – husnul