1

I am writing a simple guessing game program where the user will input a number to try and guess a randomly generated number.

If they get the number right I want to give them the option to play again.

Here is my code:

public class GuessingGame {
    private Random num = new Random();       
    private int answer = num.nextInt(10);   
    private int guess;  
    private String playAgain;  

    public void inputGuess(){
        System.out.println("Enter a number between 1 and 10 as your first guess: ");
        Scanner input = new Scanner(System.in);
        guess = input.nextInt(); 
        do{
        if (guess < 1 || guess > 10){
            System.out.println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        }else if (guess > answer){
            System.out.println("Too high, Try Again: ");
            guess = input.nextInt();
        }else if (guess < answer){
            System.out.println("Too low, Try Again: ");
            guess = input.nextInt();
        }

        }while (guess != answer);

        System.out.println("Congratulations, You guessed the number!");
        System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
        playAgain = input.nextLine();
        if(playAgain == "Y" || playAgain == "y"){
            System.out.println("Enter a number between 1 and 10 as your first guess: ");
            guess = input.nextInt(); 
        }

    }
}

The game plays through but when the user is prompted to play again nothing happens?

Any suggestions?

5
  • 4
    Don't compare strings with ==. Instead do if (playAgain.equals("Y")). Commented Oct 14, 2014 at 18:23
  • you need another loop Commented Oct 14, 2014 at 18:24
  • When the user enters "Y", you need to start the loop all over again. Commented Oct 14, 2014 at 18:25
  • Exactly what @Arvy said. Also, Random.nextInt(10) gives you a value between 0 - 9 so you should either say Random.nextInt(11) OR change your first if statement to if(guess < 0 || guess > 9) Commented Oct 14, 2014 at 18:25
  • There are plenty of things wrong: you are comparing strings with ==, you are generating a number from 0-9 (try Random.nextInt(11)), and you forget to catch the return character at the end of scan.nextInt() [which is why it is not prompting you to restart] [try putting: input.nextLine(); in your do loop after the if statements...], also you are looping it incorrectly. Commented Oct 14, 2014 at 18:28

8 Answers 8

2

Here is the completed code, fully working and tested... without using recursion.. and everything fixed.

    public static void main(String[] args)
    {
    String playAgain = "";
    Scanner scan = new Scanner(System.in);

    do
    {
        ClassName.inputGuess();
        System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
        playAgain = scan.nextLine();
    }
    while(playAgain.equalsIgnoreCase("Y"));
    System.out.println("Thanks for playing!");
}

public void inputGuess()
{
    Random num = new Random();
    int answer = num.nextInt(10)+1;
    Scanner input = new Scanner(System.in);
    int guess;

    System.out.println("Enter a number between 1 and 10 as your first guess: ");
    guess = input.nextInt(); 

    do
    {
        if (guess < 1 || guess > 10)
        {
            System.out.println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        }
        else 
            if (guess > answer)
            {
                System.out.println("Too high, Try Again: ");
                guess = input.nextInt();
            }
            else 
                if (guess < answer)
                {
                    System.out.println("Too low, Try Again: ");
                    guess = input.nextInt();
                }
        input.nextLine();

    }
    while (guess != answer);

    System.out.println("Congratulations, You guessed the number!");
}
Sign up to request clarification or add additional context in comments.

3 Comments

This works but I have a few questions. At the end of the do/while in inputGuess you have included input.nextLine(); Why is that? I don't have it in my code and it works fine.
Also why do you have to initialize the the playAgain string in main with "";
@macattack The input.nextLine() was put in to solve the catch of the return character (\n), it may work without it... and i initialized the playAgain string within main to "" for the sake of initializing it... no specific reason.
2

Do the following and your code will work :

  1. Replace all input.nextInt(); with Integer.parseInt(input.nextLine());
  2. Replace (playAgain == "Y" || playAgain == "y") with (playAgain.equalsIgnoreCase("Y"))
  3. Initialise answer inside inputGuess() in starting instead.
  4. Replace the body of if(playAgain.equalIgnoreCase("Y")) with inputGuess();

When you enter integer value through console it also contain a \n(next line) in it. But when you use nextInt(), it doesn't read this \n, but then when you tried to get next line with input.nextLine(), it looks for \n(next line) which is already there from integer entry and having nothing after that. Code look for "Y" or "y" and breaks because it doesn't found any of them.

That is why Integer.parseInt(input.nextLine()); works here

Comments

1

Here is the code:

private Random num = new Random();

private int answer = num.nextInt(10) +1;

private int guess;

private String playAgain;

Scanner input = new Scanner(System.in);

public void inputGuess(){
    System.out.println("Enter a number between 1 and 10 as your first guess: ");

    guess = input.nextInt();
    do{
        if (guess < 1 || guess > 10){
            System.out.println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        }else if (guess > answer){
            System.out.println("Too high, Try Again: ");
            guess = input.nextInt();
        }else if (guess < answer){
            System.out.println("Too low, Try Again: ");
            guess = input.nextInt();
        }

        if(guess == answer) {
            System.out.println("Congratulations, You guessed the number!");
            System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
            playAgain = input.nextLine();
        }

    }while (!playAgain.equals("Y") && !playAgain.equals("y"));
}

You just need to introduce the winning/losing logic inside the while, and the condition will be the ending/continue flag.

Another thing is always remember when comparing strings to use the equals method, since the == will compare the object reference and not the String value, in some cases == will return true for equal string since how JVM stores the Strings, but to be sure always use equals.

2 Comments

Your code doesn't check is random is from "1 to 10". In this case answer can be from "0 to 9".
You are right Alvin, to make it from "1 to 10" we need to add 1, I will edit the answer. Thanks!
0

Try something like this:

public void inputGuess(){
        System.out.println("Enter a number between 1 and 10 as your first guess: ");
        Scanner input = new Scanner(System.in);
        guess = input.nextInt();
        playAgain = "Y";
        do{
        if (guess < 1 || guess > 10){
            System.out.println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        }else if (guess > answer){
            System.out.println("Too high, Try Again: ");
            guess = input.nextInt();
        }else if (guess < answer){
            System.out.println("Too low, Try Again: ");
            guess = input.nextInt();
        }

        if(guess == answer)
        {
            System.out.println("Congratulations, You guessed the number!");
            System.out.println("Would you like to play again? Enter Y to play or N to quit: ");
            input.nextLine();
            playAgain = input.next();
            answer = num.nextInt(10);
            guess = -1;
            if(!playAgain.equalsIgnoreCase("N"))
            {
                System.out.println("Enter a number between 1 and 10 as your first guess: ");
                guess = input.nextInt();
            }
        }

        }while (!playAgain.equalsIgnoreCase("N"));

    }

You need your code for checking if they want to play again inside the loop. This way you wait until they have guessed the number correctly then ask if they want to play again. If they do you restart the process if they don't you exit the loop.

Comments

0

Some of the solution I see above aren't correct. The random number, you need to add 1 to get between 1 and 10, also you need to compare with equals. I use case insensitive here.

The following code works as you need it.

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

public class Test2 {
    private static Random num = new Random();
    private static int answer = 0;
    private static int guess;
    private static String playAgain;

    public static void main(String[] args) {
        inputGuess();
    }

    // Guess Method.
    public static void inputGuess(){
        // create answer.
        answer = 1+ num.nextInt(10);

        System.out.println("Enter a number between 1 and 10 as your first guess: ");
        Scanner input = new Scanner(System.in);
        guess = input.nextInt(); 
        do{
        if (guess < 1 || guess > 10){
            System.out.println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        }else if (guess > answer){
            System.out.println("Too high, Try Again: ");
            guess = input.nextInt();
        }else if (guess < answer){
            System.out.println("Too low, Try Again: ");
            guess = input.nextInt();
        }

        }while (guess != answer);

        System.out.println("Congratulations, You guessed the number!");
        System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
        playAgain = input.nextLine();
        if( playAgain.equalsIgnoreCase("Y") ){ 
            inputGuess();
        }

    }
}

2 Comments

What do you mean @user2494817? Why is recursion a bad idea for the if statement?
@user2494817 Using recursion should be avoided as much as possible. But in OP's case I think there is no issue. The OP's code will change too much if not done that. And speed is not an issue here. It is just a simple program.
0

By now, you would have already guessed the right way to do it. Here is how I will approach it

public class Test {
    public static void main (String...a) {
        inputGuess();
    }
    public static void inputGuess() {

        Scanner input = new Scanner(System.in);
        String playAgain = "Y";
        int guess;
        Random ran = new Random();
        int answer = ran.nextInt(10) + 1;
        while (playAgain.equalsIgnoreCase("Y")) {
            System.out.println("Enter a number between 1 and 10 as your first guess: " + answer);
            guess = input.nextInt(); 
            do {
                if (guess < 1 || guess > 10) {
                    System.out.println("That is not a valid entry. Please try again: ");
                    guess = input.nextInt();
                } else if (guess > answer) {
                    System.out.println("Too high, Try Again: ");
                    guess = input.nextInt();
                } else if (guess < answer) {
                    System.out.println("Too low, Try Again: ");
                    guess = input.nextInt();
                }
            } while (guess != answer);

            System.out.println("Congratulations, You guessed the number!");
            System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
            input.nextLine();
            playAgain = input.nextLine();
            answer = ran.nextInt(10) + 1
        }           
    }
}

Comments

0

This code can serve your purpose...

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

public class GuessingGame 
{
private Random num = new Random();
private int answer ;
private int guess;
private String playAgain;

public void inputGuess() 
{         
    answer = num.nextInt(11);
    System.out.println("Enter a number between 1 and 10 as your first guess: ");
    Scanner input = new Scanner(System.in);
    guess = input.nextInt();
    do {            
        if (guess < 1 || guess > 10) {
            System.out
                    .println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        } else if (guess > answer) {
            System.out.println("Too high, Try Again: ");
            guess = input.nextInt();
        } else if (guess < answer) {
            System.out.println("Too low, Try Again: ");
            guess = input.nextInt();
        }

    } while (guess != answer);

    System.out.println("Congratulations, You guessed the number!");
    System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
    do
    {           
        playAgain = input.nextLine();

    }while(playAgain.length()<1);

    if (playAgain.trim().equalsIgnoreCase("y"))
    {
        inputGuess();           
    }
    else
    {
        System.out.println("Good Bye!!!");
    }

}

public static void main(String[] args) {
    new GuessingGame().inputGuess();
}
   }

Comments

0

one issue :

Do not compare the content of two strings by == which just you should use equals()

Imagine the right answer is one in this case

Follow this as your blue print sample

  int answer = 0;
  String yes = "";
  Scanner input = new Scanner(System.in);
  do{
    do{
        System.out.println("Enter your number");
        answer = input.nextInt();
  } while ( answer != 1);
      System.out.println("Would you like to play again?");
      yes = input.next();
  } while ( yes.equalsIgnoreCase("yes"));

output:

enter image description here

1 Comment

@SamIam is it better now?

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.