Hi,
I have written a number guessing game in java, where the user can select the number of guesses and the range of random numbers. It will display higher and lower and correct however it will not calculate when the number of guesses has been exceeded and the appropriate message. I believe the error is in the for loop in my game class.

public abstract class Game {

    protected int guess;
    protected int random,  range;
    private String msg;

    public abstract void setup(int r, int g);

    public String compareGuess(int userRandom) {
        int i;

        for (i = guess; i > 0; i--) {
            if (userRandom < random) {
                msg = "Higher";
            } else if (userRandom > random) {
                msg = "Lower";
            } else if (userRandom == random) {
                msg = "Correct";
            } else {
                msg = ("Sorry the correct number was " + random);
            }


        }
        return msg;
    }
}

The method compareGuess should be inside a for-loop not a for-loop inside the method. The way you have you iterate, but the value "userRandom" doesn't change, so the same if is executed all the time.

You need to have the method inside the loop and ask the user each time to enter a new number. Then, if it is not found print the appropriate message and continue with the looping. If found use the "break;" command to exit the loop and set a boolean flag to true.

If the number is not guessed correctly the loop will finish and outside the loop you will check the boolean flag if it was true or false? Don't forget to instantiate the boolean variable correctly

This article has been dead for over six months. Start a new discussion instead.