How to fix the replay function in this code? - java

I am coding this to ask the player to guess a random number. After they finish the guessing or get the correct answer, the program will end. This part works ok for now. However, the second part, when they finish the first round, I want the program to ask the user if they want to replay. But the function for "I want to replay" is not working here. Can anyone help how to modify this?
public static void main( String [] args )
{
Scanner scan = new Scanner(System.in); //create scanner object
int maxNumber = 0; //initial value for MaxNumber
int userGuess = 0; //initial value for UserGuess
int totalGuesses = 0; //initial value for TotalGuesses
int randomNumber = 0; //initial value for RandomNumber
int maxAttempts = 0; //initial value for MaxAttempts
int end = 0;
int replay = 0;
do
{
System.out.println( "Please enter a maximum value: " ); //Ask user to input a max number
maxNumber = scan.nextInt(); //set MaxNumber to user input
System.out.println( "Please enter a maximum attempts: " ); //Ask user to input max attempts
maxAttempts = scan.nextInt(); //set Attempts to user input
randomNumber = (int) ( maxNumber * Math.random() ) + 1; //generate a secret number
System.out.println( "A new secret number has been generated"
+ "\n Input your guess" ); //ask user to input a guess
while (totalGuesses < maxAttempts)
{
userGuess = scan.nextInt(); //set UserGuess to user input
totalGuesses++; //increment total number of guesses by 1
if (userGuess < randomNumber) //while user's guess is less than the secret number
{
System.out.println("Sorry, that is too low! Please try again.");
}
else if (userGuess > randomNumber) //while user's guess is greater than the secret number
{
System.out.println("Sorry, that is too high! Please try again.");
}
else if (userGuess == randomNumber) //if user guesses correctly
{
System.out.println(" Your guess is correct!" // let user know the guess is correct
+ "\n Total number of guesses: " + totalGuesses); // display total number of guesses
}
while (userGuess == randomNumber | totalGuesses == maxAttempts)
{
System.out.println("Would you like to play again? Please input 1 for Yes or 2 for no and press enter.");
//ask user if they would like to play again
replay = scan.nextInt();
if (replay == 1);
{
end == 0;
}
if (replay == 2);
{
end == 1;
System.out.print("Thanks for playing!");
}
}
}
}while (end == 0);
}
I expect when user put 1, they can replay. And the program should stop when they enter 2.

Related

One expected line of output is not printed

import java.util.Random;
import java.util.Scanner;
public class Activity3 {
public static void main(String[] args) {
//Variables
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10);
do {
System.out.println("Guess the random generated number of the machine from 1-10");
int guess = input.nextInt();
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
} else if (guess <= 0 && guess >= 11) {
System.out.println("Invalid Number!");
}
if (guess > 1 && guess < 10){
System.out.println("You Lose:<");
}
System.out.println("Do you want to try again?");
} while (input.next().equalsIgnoreCase("YES"));
input.close();
}
}
If I guess the correct number it outputs " you win!".
If I guess wrong it outputs "you lose". But If I guess a number that isn't in 1-10 it doesn't output the "Invalid Number" and just proceeds to output the "Do you want to try again?".
Random#nextInt(int) will return a value from 0 to bound - 1, so it's possible that the guess could be 0 in your code. You'd correct this by adding 1 to the guess, for example int num = Machine.nextInt(10) + 1;
Look at your logic...
else if(guess <= 0 && guess >= 11) {
if guess <= 0 AND guess >= 11 ... well, that's impossible.
I would change your logic flow, focusing on "happy paths" first.
That is, is the input within the acceptable range? If so, is guess == num if so, you win, otherwise print error messages.
For example...
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10) + 1;
boolean done = false;
do {
System.out.println("Guess the random generated number of the machine from 1-10");
// Read the WHOLE line of text, removing the new line from the
// buffer which would otherwise be left by Scanner#nextInt
// and would cause no end of issues
String text = input.nextLine();
try {
// Try and parse the text to an int
int guess = Integer.parseInt(text);
if (guess >= 1 && guess <= 10) {
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
num = Machine.nextInt(10) + 1;
System.out.println("Would you like to play another game? (Yes/No)");
} else {
System.out.println("Incorrect, guess again");
System.out.println("Do you want to try again? (Yes/No)");
}
// Prompt the user to try again or play another game
text = input.nextLine();
done = !"yes".equals(text.toLowerCase());
} else {
System.out.println("Out of range");
}
} catch (NumberFormatException exp) {
System.out.println("Not a valid number");
}
} while (!done);

How to let the user attempt many times?

import java.util.Scanner;
import java.util.Random;
/*
* 1) the user can attempt many times and you need to display the number of successful attempt
* 2) the range of random number 1..49
* 3) output >> You successfully guess the number in 16 attempts
* 4) output >> Do you want to play again?
* */
public class GuessingGame {
public static void main(String[] args) {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count=0;
String in;
char again;
System.out.println("Welcome to Guessing Game");
do {
number = randNum.nextInt(50); // random number in the range of 1..50
for(int i=0; i<5; i++)
{
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
if(guessNumber > number)
{
System.out.println("Too big");
}else if(guessNumber < number)
{
System.out.println("Too small");
}else
{
System.out.println("Success");
count+=1;
return;
}
}
System.out.println("You successfully guess the number in "+count);
System.out.println("Do you want to play again? ");
in = uInput.nextLine();
again = in.charAt(0); //again will hold the first character from in var
}while(again =='Y'|| again =='y');
System.out.println("Guessing game terminate, thank you");
}
}
public static void main(String[] args) {
System.out.println("Welcome to Guessing Game");
guessNumber();
System.out.println("Guessing game terminate, thank you");
}
private static void guessNumber() {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count = 0;
String in;
char again;
boolean isCorrect = false;
number = randNum.nextInt(50); // random number in the range of 1..50
while (!isCorrect) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
count += 1;
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
isCorrect = true;
}
}
System.out.println("You successfully guess the number in " + count + " attempts");
System.out.println("Do you want to play again? yes/no");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
if (again == 'Y' || again == 'y') {
guessNumber();
}
}
All you have to do is to replace your do while loop with a while loop. But the point is that you must set an initial value 'Y' to your again char to start the while loop. the condition of the loop will be just the same. The code will be like : char again = 'Y';
while (again == 'Y' || again == 'y') {
System.out.println("Welcome to Guessing Game");
number = randNum.nextInt(50);
for (int i = 0; i < 5; i++) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt();
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
count += 1;
break;
}
}
System.out.println("You have successfully guessed the number for " + count + " times");
System.out.println("Do you want to play again? ");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
}
System.out.println("Guessing game terminate, thank you");
I must note that your count variable, contains the number of games which user has guessed the number successfully, and not the number of attempts during a single game. If you want to handle this too, create attempts variable inside the while loop and increase it whenever the user attempts.
Also I changed the line in = uInput.nextLine(); to in = uInput.next(); because I believe your scanner input will be skipped.

Can a program repeat when a user ends the program while it is running?

This is a Hi-Lo number guessing game code, and the program ends either when the user gets the correct number or enters -1 while playing the game.
Here, I was wondering if it is possible to make the program run again even after the user enters -1 and the game ends, for example, in a situation where the user feels like restarting the game without finishing the first game.
import java.util.Random;
import java.util.Scanner;
public class HighLowGame {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
int guess = scanner.nextInt();
**//if user enters -1, the game ends
if(guess == -1){
break;
}**
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
count = 0;
System.out.println("Would you like to play the game again?(yes/no): ");
String another = scanner.next();
if (another.equalsIgnoreCase("no")) {
break;
}
// if the user wants to play the game one more time, it starts again
else {
number = generator.nextInt(100) + 1;
System.out.println("Please guess the number(Enter -1 to quit): ");
}
}
}
}
}
You can just put the game into a method, and when the method ends, you just ask them.
Main:
public static void main(String[] args){
boolean flag = true;
while(flag){
play();//play the game
Scanner input = new Scanner(System.in);//read the respound
System.out.println("want to play again?");
if(input.nextLine().equal("no"){//Want to play? BTW: I'm assuming you only enter "no" or "yes"
flag = false;//Don't want to play
}
}
}
And the method:
public static void play(){
//create scanner, variables and a random number
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
//prompt user to enter a number
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
//user enters a number
int guess = scanner.nextInt();
//if user enters -1, the game ends
if(guess == -1){
break;
}
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
//displays the message and the attempt count
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
}
}
}
BTW: you said when the user enters -1, you end the game, then why in the world do you want to ask the user again ?_?

Beginner Java Secret Number Guessing Program

This Java program is supposed to ask the user to input a maximum value, and then generate a random number between 1 and that maximum value. The user then guesses what the value is until they get it right. When the user is incorrect, the program tells them that they're too high or too low and increments the number of guesses. If the user is correct, the program displays the total number of guesses and asks the user if they would like to play again.
The issue I keep having is that sometimes, when I input a guess, the program skips over telling me I was too high, too low, or correct, and simply asks me if I would like to play again. I can't figure out why this is happening, and it seems to happen randomly.
import java.util.Scanner;
public class GuessNumber
{
public static void main (String [] args)
{
Scanner in = new Scanner (System.in); //create scanner object
int maxNumber = 0; //declare variables
int userGuess = 0;
int totalGuesses = 0;
int secretNumber = 0;
String replay = "";
System.out.println("Welcome to the Secret Number Generator!");
do
{
System.out.println("Please input a maximum value for the secret number and press enter."); //prompt user to input a maximum value
maxNumber = in.nextInt();
secretNumber = (int) ((Math.random() * maxNumber) + 1); //generate the secret number
System.out.println("A new secret number has been chosen!"
+ "\nWhat do you think it is? Input your guess and press enter."); //prompt user to input a guess
userGuess = in.nextInt();
while (userGuess < secretNumber) //while user's guess is less than the secret number
{
System.out.println("Sorry, that is too low! Please try again."); //prompt user to input another guess; increment total number of guesses by 1
userGuess = in.nextInt();
totalGuesses ++;
}
while (userGuess > secretNumber) //while user's guess is greater than the secret number
{
System.out.println("Sorry, that is too high! Please try again."); //prompt user to input another guess; increment total number of guesses by 1
userGuess = in.nextInt();
totalGuesses ++;
}
if (userGuess == secretNumber) //if user guesses correctly
{
System.out.println("Nice job! Your guess, " + secretNumber + " is correct!" //congratulate and display total number of guesses
+ "\nTotal number of guesses: " + totalGuesses);
}
System.out.println("Would you like to play again? Please input \"Yes\" or \"No\" and press enter."); //ask user if they would like to play again
replay = in.next();
while (!replay.equalsIgnoreCase("Yes") && !replay.equalsIgnoreCase("No") //in case of invalid input
&& !replay.equalsIgnoreCase("\"Yes\"") && !replay.equalsIgnoreCase("\"No\""))
{
System.out.println("Sorry, that is an invalid input. Please input \"Yes\" or \"No\" and press enter.");
replay = in.next();
}
}
while(replay.equalsIgnoreCase("Yes") || replay.equalsIgnoreCase("\"Yes\"")); //replay while user says yes
if (replay.equalsIgnoreCase("No") || replay.equalsIgnoreCase("\"No\"")) //if user says no
{
System.out.print("Thanks for playing!");
}
} //end of main method
} //end of class GuessNumber
you have multiple while loops which doesn't make sense. if user enters bigger number then enter small one it will skip it.
you can shrink them all to one of them
while (userGuess != secretNumber){
if(userGuess > secretNumber){
//too high
} else if(userGuess < secretNumber){
//too low
} else{
//nice got it
}
}
//do you want to play again
...
Don't use while loops for single evaluation conditions. Replace your three inner while loops with something like this (pseudocode):
int guess = readInteger()
while guess != number
if guess < number print "too low"
if guess > number print "too high"
assert guess == number
print "you guessed correctly; good job!"
And then run that through the game loop that keeps the game going.
Looks like you are having some looping troubles, and like the others suggest please avoid so many unnecessary nested loops when a simple selection structure like "if else" or "select case" will work. Should save you some fuss that way too.
To make your app run more predictably I would suggest throwing the "game" logic into a method. Here is an example that runs. Hope it helps you out some!
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String replay = "";
do {
runGame(); //run method to guess number
System.out.println("Play again? Enter Yes or No");
replay = in.nextLine().toLowerCase();
}
while(!replay.equals("no"));
}
private static void runGame() {
Scanner in = new Scanner(System.in); //create scanner object
int maxNumber = 0; //declare variables
int userGuess = 0;
int totalGuesses = 0;
int secretNumber = 0;
System.out.println("Welcome to the Secret Number Generator!");
System.out.println("Please input a maximum value for the secret number and press enter."); //prompt user to input a maximum value
maxNumber = in.nextInt();
secretNumber = (int) ((Math.random() * maxNumber) + 1); //generate the secret number
System.out.println("A new secret number has been chosen!" + "\nWhat do you think it is? Input your guess and press enter."); //prompt user to input a guess
userGuess = in.nextInt();
while (userGuess != secretNumber) {
if (userGuess < secretNumber) {
System.out.println("Sorry, that is too low! Please try again."); //prompt user to input another guess; increment total number of guesses by 1
} else if (userGuess > secretNumber) {
System.out.println("Sorry, that is too High! Please try again."); //prompt user to input another guess; increment total number of guesses by 1
}
else {
System.out.println("Sorry, but that's not right. Try again...");
}
totalGuesses++;
userGuess = in.nextInt();
}
System.out.println("You guessed it! After " + totalGuesses + " tries.");
}
}

How to use while loop

Ask the user to guess a number until the guess is equal random number. press 0 to quit and ask the user if they want to play again.
My problem, 0 for quit is, not working. How can I make it work with while loop?
thanks
import java.util.Random;
import java.util.Scanner;
public class Guessing
{
public static void main(String[]args){
String playAgain = "y";
final int MAX =100;
int randomNumber;
int numberofGuess = 0;
int guess ;
boolean flag=false;
Scanner input = new Scanner(System.in);
Random rand = new Random();
Scanner inputYes= new Scanner(System.in);
while(playAgain.equalsIgnoreCase("y"))//do
{
System.out.println("Guess a number between 1 and "+ MAX );
randomNumber = rand.nextInt(MAX) +1;
numberofGuess = 0;
System.out.println( "enter a guess(0 to quit):");
guess= input.nextInt();
numberofGuess++;
if(guess >0)
if (guess == randomNumber)
{
System.out.println("you guessed corect.");
System.out.println("you guessed " +numberofGuess+ " times");
}
else if(guess < randomNumber)
System.out.println("you guess is too low.");
else if(guess > randomNumber)
System.out.println("you guess is too high.");
System.out.println("Do you want to play again? (y/n)");
playAgain = inputYes.nextLine();
}//while(playAgain.equalsIgnoreCase("y"));
}
}
Your loop runs until the expression in parantheses is false:
while (true) {
// this will be executed forever
}
while (false) {
// this will never be executed
}
a = 0;
while (a == 0) {
a = 1;
// this will be executed exactly once, because a is not equal 0 on the second run
}
guess = 1
while (guess != 0) {
// this will executed until the user enters "0"
readln(guess);
}
Please keep in mind that this is pseudo code. It will not compile.

Categories