无限的do-while循环

时间:2014-11-17 18:33:54

标签: java infinite-loop do-while

我的代码中存在无限循环,我对如何解决它感到困惑。如果有人能指出我正确的方向或帮助我,那么我真的很感激。谢谢。 这是方法:

public static void random(){
    int rand = (int) (Math.random() * 11); 
    Scanner input = new Scanner(System.in); 
    System.out.print("Enter a guess: ");
    int guess = input.nextInt();
    if (guess == rand){
        do {
            System.out.println("Your guess is " + guess + "."); 
            System.out.println("Your guess is correct! Yay!"); 
        } while (guess == rand); 
    }
    if (guess < rand){
        do {
            System.out.println("Your guess is " + guess + ".");
            System.out.println("Your guess is too low. Guess again"); 
        } while (guess!= rand);
    if (guess > rand){
        do {
            System.out.println("Your guess is " + guess + ".");
            System.out.println("Your guess is too high. Guess again");
        } while (guess > rand);
    }

2 个答案:

答案 0 :(得分:2)

int guess = Integer.MIN_VALUE;
do {
    guess = input.nextInt();
    System.out.println("Your guess is " + guess + ".");
    if (guess == rand)
        System.out.println("Your guess is correct! Yay!"); 
    else if (guess < rand)
        System.out.println("Your guess is too low. Guess again"); 
    else
        System.out.println("Your guess is too high. Guess again");
} while (guess != rand);

答案 1 :(得分:1)

由于你的while循环,你的代码处于无限循环中。如果用户猜测低于rand,则代码将进入while循环并继续无限循环。这是一个可能的解决方案

public static void random(){
    int rand = (int) (Math.random() * 11); 
    Scanner input = new Scanner(System.in); 
    System.out.print("Enter a guess: ");
    boolean guessed = false;

    while(guessed == false){
    int guess = input.nextInt();

    if(guess == rand){

        System.out.println("Your guess is " + guess + "."); 
        System.out.println("Your guess is correct! Yay!"); 
        guessed = true;
    }
    if(guess < rand){

            System.out.println("Your guess is " + guess + ".");
                System.out.println("Your guess is too low. Guess again"); 
                guessed = false;
    } 
    if(guess > rand){

            System.out.println("Your guess is " + guess + ".");
            System.out.println("Your guess is too high. Guess again");
            guessed = false;
    }
    }
}