不会停止循环

时间:2015-10-25 23:51:11

标签: java loops

编写一个生成随机数(1到10之间)的程序,并要求用户猜出该数字是多少。如果用户的猜测高于随机数,程序应显示“太高,再试一次。”如果用户的猜测低于随机数,程序应显示“太低,再试一次。”程序应该使用重复的循环,直到用户正确猜出随机数。

这是我的代码,当我运行它时,它不会停止循环,我不知道为什么。谢谢!!

/////guess/////
import java.util.Random;
import java.util.Scanner;
public class guess
{
  public static void main (String [] args)
  {
    Random rand = new Random();
    int numberToGuess =rand.nextInt(10);
    Scanner input=new Scanner(System.in);
    int guess;
    boolean win =false;
      while (win == false)

      System.out.println("Guess a number between 1 and 10");
      guess = input.nextInt();

      {
        if(guess == numberToGuess)


        win=true;
      }
       if(guess<numberToGuess)
       {

         System.out.println("Your guess is too low");
       }

       {
       if (guess > numberToGuess)

         System.out.println("Your guess is too high");
         System.out.println("You win!");
         System.out.println("The number was"  +numberToGuess);
       } 
  }
}

2 个答案:

答案 0 :(得分:2)

这不仅适用于while语句; iffor语句也受此影响。

如果while语句未包含在块中,则// Without curly braces, the println is the only thing in the loop. while (win == false) System.out.println("Guess a number between 1 and 10"); // This isn't part of the loop! guess = input.nextInt(); 语句将只执行 next 行。

while(!win) {
    // ALL of the logic you want to execute while win is false
}

你可以通过确保你想要循环的所有内容都包含花括号来解决这个问题:

For TIDtoCell = 4 To 17 Step 1
    Sheets("Rapport SNN").["C" & TIDtoCell].FormulaLocal = "=cboTerminalID" & TIDtoCell & ""
Next TIDtoCell

答案 1 :(得分:1)

如果您已经按原样复制了代码,请查看您的while循环没有{},以便继续打印

System.out.println("Guess a number between 1 and 10");

直到win更改,在此代码中它才会赢得