Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Natalia Henderson
Natalia Henderson
5,190 Points

Why is it giving me an infinite loop?

Hey, so I'm writing this guessing game program where the user needs to guess the number that the computer picked between one and 100 (inclusive). However, the only output I get is an infinite loop of "Too low." My code seems perfectly fine to me, any thoughts?

import java.util.Random; 
import java.util.Scanner;

public class GuessingGameV1
{
    public static void main(String[] args)
    {
        int number_guesses = 0;
        Random rand = new Random(); 
        int rand_int = rand.nextInt(101); 

        Scanner in = new Scanner(System.in);  
        int user_guess = in.nextInt(); 

        boolean win = false;

        while(win == false)
        {   
            if (user_guess == rand_int){
                win = true; 
            }
            else if (user_guess > rand_int) {
                System.out.println("Too High");    
            } 
            else if (user_guess < rand_int) {
                System.out.println("Too Low");     
            }
            number_guesses++;
        }
        System.out.println("Congratulations");
        System.out.println("The random number was " + rand_int);
        System.out.println("Number of guesses " + number_guesses);
    }
}

1 Answer

You need to update user_guess with a new guess inside the loop. Otherwise unless the random number is guessed on the first try the loop will never end.