2

I apologize if this question is uber-simplistic, but I'm still in the early stages of learning Java. I have an example program that calls other methods within the class, and I'm not totally following a few of the elements - hoping someone can clarify. It's a simply random number guessing game and it works fine, but I want to better understand some components. Specifically:

  • There is a boolean variable (validInput) that is declared but never appears to be used anywhere in the methods
  • There are 2 methods (askForAnotherRound and getGuess) with a 'while' loop that just has 'true' as the variable(?) - i.e. "while (true)."

This code is directly from the example in the book and, again, it works. I just want to better understand those 2 elements above. (I think the validInput variable is not useful as when I 'comment out' that line the code still executes). I'm curious, though, about the "while (true)" element. There is an option to set, in the askForAnotherRound, to set the return value to false (ending the program). Are boolean methods defaulted to 'true' when they are first executed/called?

Again...understand this is probably a super-simple question for most folks on here, but as a newb I just want to understand this as best I can...

Thanks!!!

// Replicates the number guessing game using 4 separate methods.

import java.util.Scanner;

public class GuessingGameMethod2
{
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args)
    {
        System.out.println("Let's play a guessing game!");
        do
        {
            playARound();
        }while (askForAnotherRound());
        System.out.println("Thanks for playing!");
    }

    public static void playARound()
    {
        boolean validInput;
        int number, guess;
        String answer;

        //Pick a Random Number
        number = getRandomNumber();

        //Get a guess
        System.out.println("\nI'm thinking of a number between 1 and 10.");
        System.out.print("What do you think it is? ");
        guess = getGuess();

        //Check the guess
        if (guess == number)
            System.out.println("You're right!");
        else
            System.out.println("You're wrong! The number was " + number + ".");
    }

    public static int getRandomNumber()
    {
        return (int)(Math.random() * 10) + 1;
    }

    public static int getGuess()
    {
        while (true)
        {
            int guess = sc.nextInt();
            if (guess < 1 || guess > 10)
            {
                System.out.print("I said, between 1 and 10. Try again");
            }
            else
                return guess;
        }
    }

    public static boolean askForAnotherRound()
    {
        while (true)
        {
            String answer;
            System.out.print("\nPlay again? Y or N: ");
            answer = sc.next();
            if (answer.equalsIgnoreCase("Y"))
                return true;
            else if (answer.equalsIgnoreCase("N"))
                return false;
        }
    }
}
1
  • Thanks all for the rapid responses!! Makes much more sense now :-) Commented Sep 29, 2018 at 2:55

4 Answers 4

1

I don't see boolean validInput being used either. But if it were to be used somewhere it would probably be to check that you guess satisfies 1 <= guess <= 10.

When it comes to askForAnotherRound and getGuess here's what you should know:

while(true) is always executed. One way you can get out of the while loop is if you use the break statement or if the loop is in a function you can return something. The method askForAnotherRound() will always return either true or false. Depending on the returned value of askForAnotherRound() you will either play another round or not. Note that when you have

    `do{
    ...    
    someActions()
    ...
    }while(booleanValue)`

someActions() will be executed at least once before it checks for the value of booleanValue which, if it turns out false you'll exit out of the do/while loop. Boolean methods do not default to anything, you have to give them a value.

Hope this helps! I'm also in the process of learning Java right now, so good luck!

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks so much for the input!! It makes much more sense now - one of those things where I was thinking, "OK, it works...but WHY does it work?" which can be almost more maddening than figuring out why something DOESN'T work...
I'm happy to have helped you! Please consider accepting the answer or upvoting. It's my first answer ever on stackoverflow and it'd make me really happy as you might imagine. Good luck learning Java!
Selected 'accepted' - apparently I can't 'upvote' since this is my first post - but again, many thanks!
1

As I see you're absolutely true about validInput - it isn't used. May be it will be used in the following chapters.

As for askForAnotherRound() - no, boolean methods don't evalute to true, by default. Even more, Java compiler throw an error if it find a method which does not return value and finish it execution in some cases.

while(true) - it's infinite loop, so it will be executed untill some instruction which interrupts loop, in general it's return statement.

askForAnotherRound() do the following: - asks user if he/she want to play again - returns true if user input "Y" - returns false if user input "Y" - asks again in all other cases(so it doesn't finish execution) and etc.

Hope it'll help

Comments

1

The validInput is indeed worthless.

The infinite loops are required to read from the console to get a valid input. e.g

while (true)
//start infinite loop
        {
            int guess = sc.nextInt();
            if (guess < 1 || guess > 10)
            {
            //continue the loop the input is not between 1-10
                System.out.print("I said, between 1 and 10. Try again");
            }
            else
                //break out of infinite loop, valid int
                return guess;
        }

If we take this method without the infinite loop, and i recommend trying this, it will simply return the value read even if it was not valid.

For example.

 return sc.nextInt();

will allow any int returned, if we returned anything outside of the bounds in the current impl it would loop again until you enter a value between 1-10

The same is also true for ask for next round, its looping until a valid input is given.

I would bet the next exercises will use the validInput var as both these methods loop until a valid input is given.

Comments

1

You are right about validInput. It is not used. And probably missed after some code change. Should be removed.

while(true) - true is not variable but a boolean constant. It will basically make program run for ever in this case unless somebody kills program. Another alternative would have been to use break to exit out of loop on some condition.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.