User input to repeat program in Java

how to make a java program repeat itself
do while loop to repeat a program java
how to ask user if they want to run program again in java
how to make a program run again in java
java do while loop with user input
java for loop user input
write a java program that asks user to input an integer and prints it until user enters 0
java yes or no loop

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?

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!");
}

CS 1063, Fall 2005 Repeated Input in Java, Repeated Input in Java (first version). import java.io.*; public Here is a second version of the program above, that uses a String, rather than a char for the reply:� 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 ag

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

Use the right loop to repeat tasks, OpenClassrooms uses cookies to improve your user experience and to optimize the platform's performance. Personalized advertising contents could also be� That’s because, when the program starts running, the user hasn’t made any guesses. Later in the program, right after each call to keyboard.nextInt, is a numGuesses++ statement. That’s how you do it — you increment the counter as soon as the user enters another guess.

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.

Java Do While Loop Example Where User Prompts to Start Program , In this example of a do-while loop, we use the Scanner class to read keyboard input. We ask the Duration: 5:55 Posted: Oct 6, 2017 I need it to repeat, yet I do not understand what I'm reading in the text on how to do it. It only covers repeating values, like a gradebook program. Anyway, I need the program to keep repeating until the user inputs "stop" as the employee name.This is my code so far: package payroll_program_2; import java.util.Scanner;

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.

Intro Java: "repeat" command (for loop), Java Tutorial - 11 - Validating User Input - Duration: 7:06. Absolute Zero( Programming Duration: 3:28 Posted: Aug 18, 2016 Hi Chris! The only problem that I see in your code is that your loop has got no exit condition. It might be helpful to have a confirmation by the user at the end to continue with the execution or not and set the variable game correctly or have a special case such as anything other than 1-99 which will break from the loop.

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();
        }

    }
}

Java while loop, Java while loop example. Following program asks a user to input an integer and prints it until the user enter 0 (zero). import java.util.Scanner;. class WhileLoop { Your program should ask user input a string and will generate the following: The Permutation with and without repetition. The Combination with and without repetition. SAMPLE DISPLAY :(the red texts are considered as inputs) WITHOUT REPETITION. Input String: ABC. Permutation : {A B C}, {A C B}, {B A C}, {B C A}, {C A B}, {C B A} Combination

Repeat Instructions: Java while Statements, That's because, when the program starts running, the user hasn't made any guesses. Later in the program, right after each call to keyboard.nextInt, is a� Java# Programing# With user input# Add two no.# C++# Object oriented programing language# Sum of two no. With user input in java# Java program#

What is the best way to get my program to repeat itself? [Solved , Win a copy of 97 Things Every Java Programmer Should Know this week in the Java in General forum! Here is my program, how do I get it to repeat after it is finished printing?: ? Scanner input = new Scanner(System.in); It might be helpful to have a confirmation by the user at the end to continue with� Java User Input The Scanner class is used to get user input, and it is found in the java.util package. To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine () method, which is used to read Strings:

Java while and dowhile Loop, we will learn how to use while and do while loop in Java with the help of examples and we In computer programming, loops are used to repeat a specific block of code until a To take input from the user, we have used the Scanner object. To make your Java program’s loops easier to write and easier to understand, you need to know how Java’s break and continue statements affect loop iterations. Java’s break statement Take a gander at the program below. The program randomly generates a number from 1 to 10, and repeatedly asks the user to guess that number.

Comments
  • Don't compare strings with ==. Instead do if (playAgain.equals("Y")).
  • you need another loop
  • When the user enters "Y", you need to start the loop all over again.
  • 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)
  • 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.
  • 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.
  • 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!
  • 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.
  • @SamIam is it better now?