簡體   English   中英

如何在循環中的嵌套if語句中結束while循環? (可能很簡單)

[英]How to end while-loop in a nested-if statement within the loop? (probably easy)

下面的代碼是數字猜謎游戲的一部分,其中計算機生成用戶指定范圍內的隨機數。 在這里,我試圖將用戶限制為10個猜測。 如果他/她超過10,則游戲結束:

int t1 = 0;//stores # of guesses

while(true){//loop begins
t1++;//increments each iteration to represent # of guesses 

if(g1!=n){//if the guess is incorrect... (n = # user is trying to guess)

if(t1>10){//# of guesses cannot exceed 10
System.out.println("\nGAME OVER\nYou have exceeded the max # of tries!");
break;}//game ends if user exceeds max # of attempts

if(g1<n){System.out.println("\nGuess Higher!\n" + t1 + "attempt(s) so far");
continue;}//guess is too low    

if(g1>n){System.out.println("\nGuess Lower!\n" + t1 + " attempt(s) so far");
continue;}}//guess is too high (loop ends)

我收到的輸出只有1/2正確。 例如,假設計算機生成的數字12在1至100的范圍內。 在用戶的第10次(最后一次)猜測中,它將打印:“ GAME OVER ...”; 但是,如果用戶的猜測太低或太高(我不希望這樣做),它也會打印。

我要進行哪些更改以更正此錯誤? 我認為這與嵌套if中的'break'語句有關。

您的問題似乎有效。 該代碼是正確的,它正在執行應做的事情。 但是,編寫相同代碼的更好,更有效的方法是:

// run a for loop that will let user guess 10 times
for (int i = 0; i < 10; i++)
{
    // see if the guessed number is incorrect
    if (g1 != n)
    {
         // check whats wrong with the number entered

         // number of guesses cannot exceed 10
         if ((i+1) >= 10)
         {
             System.out.println("\nGAME OVER\nYou have exceeded the max # of tries!"); 
         }
         else if (g1 < n)
         {
             // if user's guess is less than the number
             System.out.println("\nGuess Higher!\n" + (i+1) + "attempt(s) so far"); 
         }
         else if (g1 > n)
         {
             // if user's guess is greater than the number
             System.out.println("\nGuess Lower!\n" + (i+1) + " attempt(s) so far");
         } 
    } 
} // for loop ends

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM