简体   繁体   中英

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

The code below is part of a number guessing game, in which the computer generates a random number within a user-specified range. Here, I'm trying to limit the user to 10 guesses. If he/she exceeds 10, then the game ends:

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)

The output I recieve is only 1/2 correct. For example, assume the computer has generated the number 12 in a range of 1-100. On the user's 10th (last) guess, it will print: "GAME OVER..."; however, it will also print if the user's guess is too low or tooh igh, which I don't want.

What change do I make to correct this error? I think it has to do with the 'break' statement in the nested-if.

Your question seems to be working. The code is right and it is doing what it is supposed to do. But, the better and more effective way to write the same code is :

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM