简体   繁体   English

如何在循环中的嵌套if语句中结束while循环? (可能很简单)

[英]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. 在这里,我试图将用户限制为10个猜测。 If he/she exceeds 10, then the game ends: 如果他/她超过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)

The output I recieve is only 1/2 correct. 我收到的输出只有1/2正确。 For example, assume the computer has generated the number 12 in a range of 1-100. 例如,假设计算机生成的数字12在1至100的范围内。 On the user's 10th (last) guess, it will print: "GAME OVER..."; 在用户的第10次(最后一次)猜测中,它将打印:“ 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. 我认为这与嵌套if中的'break'语句有关。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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