2016-03-14 31 views
-2

我試圖在5個數學題之後打破循環。 Return語句在此公共靜態中是必需的。 我似乎無法讓程序打破循環。5個問題後需要跳出一個while循環

count=0; 
while(count < 5) 
{ 
    System.out.println("Please answer the following problem: "); 
    System.out.println(randomInt1 + "+" + randomInt2 + "="); 
    answer = keyboard.nextDouble(); 

    if(answer != (randomInt1 + randomInt2)) 
    { 
     System.out.println("Sorry, that is not correct."); 
    }  
    else if(answer == (randomInt1 + randomInt2)) 
    { 
     System.out.println("Nice!"); 
    } 
    count++; 
    break; 
} 
+1

你有'break;'在最後,所以你打破循環。這是在調試器中單步執行代碼的地方,它會告訴你問題出在哪裏。 –

+0

@PeterLawrey我對此很新,並且不知道調試器。 –

+0

代碼中的中斷是我可以發現每次都會詢問不同問題的唯一方式。如果沒有休息,它會提出相同的問題五次,然後提出另一個問題5次 –

回答

3

移動breakelse if內。當你的回答正確或者當count大於或等於5時,你的循環將停止。

目前,你的循環只執行一次,然後你突破它。另外,如果你想問一個不同的問題,那麼你每次都需要新的隨機數字。

+0

沒有'休息',它會一遍又一遍地提出同樣的數學問題,並且一次又一次地提出另一個數學問題。 –

+0

我想我明白你在說什麼。查看編輯 –

+0

如何檢查這些內容? –

-2

不使用break,它會在條件失敗時自動停止.remove else如果使之成爲其他情況,如果值不相等,則表示在其他情況下它應該相等。如果需要停止時用戶輸入一個正確的值,只需在if語句內移動break語句,如果他正確回答了它,那麼它會一直提問相同的問題,直到條件失敗。

count=0; 

while(count < 5) 
{ 
System.out.println("Please answer the following problem: "); 
System.out.println(randomInt1 + "+" + randomInt2 + "="); 
answer = keyboard.nextDouble(); 

if(answer == (randomInt1 + randomInt2)) 
{ 
System.out.println("Nice!"); 
break; 
}  
else 
{ 
System.out.println("Sorry, that is not correct."); 
} 

count++; 

} 
+1

這是否編譯?你有一個語法錯誤,請檢查它。它接近else if語句。 –

+0

我沒有任何錯誤在我身邊,沒有。 –

+0

不,它會工作的很好 – Rishi0405