Beginner Java Secret Number Guessing Program - java

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

Related

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 ?_?

Java - Need my loop to not only end after three guesses but display the correct number as well

I'm trying to have my loop only occur three times. So if the user doesn't guess the correct number after their third guess then the loop ends which I have but it doesn't display what the number was. I need the number displayed after the third guess but not sure why it's not displaying the correct number.
import java.util.Scanner;
public class GuessNumberDoWhileA {
public static void main(String[] args) {
//Generate random number from 1-10
int number = (int) (Math.random()*9 + 1);
int count = 0;
//Auto Generated Method stub
Scanner Input = new Scanner(System.in);
//Tell the user to guess a number
System.out.println("Guess a number between 1 and 10");
//int guess = -1;
//while (guess != number) {
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number)
System.out.println("Correct the number was " + number);
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
else
System.out.println("The correct number is " + number);
}
System.out.println("The number was " + number);
}
}
You need a boolean variable that can be used to check whether user was able to guess the number correctly or not. Initial value of this boolean variable should be false.
You don't need the last else statement in the loop. If user guesses the number correctly, set the boolean variable to true and break out of the loop. After the loop, check if the boolean variable is false or not. If it is false, that means user was not able to guess the number, so display the correct number to the user.
If user is able to guess the number then the first if statement in the loop will print the correct number on the console and break out of the loop. It will also set the boolean variable to true, so correct number will be printed only once on the console.
boolean guessed = false;
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number) {
System.out.println("Correct the number was " + number);
guessed = true;
break;
}
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
}
if (!guessed) System.out.println("Number was: " + number);

Hi-Lo Guessing Game - Limiting number of attempts from user input & play again logic

I'm new to Java programming and taking a college course where I have an assignment to create a Hi/Lo guessing game. The game provides up to 5 attempts for the user to input a number between 1 and 100 (inclusive). The program must provide the logic back of whether the answer is too low, too high or correct. The program must provide the option to play again after either winning or the 5 failed attempts.
I've recreated this program about 10 times :(. I cannot get he logic to work to follow the instructions above. I cannot stop the tries at 5 attempts... and I cannot get the program to execute a new game.
Any help is greatly appreciated. I've spent countless hours writing and re-writing this code with MANY different results - but not the intended ones.
This is my first time posting so, I apologize if the format to post is not correct.
I've looked through more forums and examples than I care to admit and none of code I've reviewed and tried implementing have given me the results of limiting the user input to 5 tries each time and ability to play again multiple times.
Here is my code:
public class HiLoGuessingGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Initialize scanner and random number gennerator
Scanner input = new Scanner(System.in);
Random generator = new Random();
//State the rules of the game
System.out.println("The Hi-Lo Guessing Game. Guess a number between 1-100");
System.out.println("You have 5 attempts!");
/* define the variable Guess (user iput)
define the variable Answer (random generator)
define the variable Counter (track number of tries and limit to 5)
define the variable PlayAgain (Y/N question)*/
int guess = 0;
int answer = generator.nextInt(100)+1;
int counter = 1;
String playAgain;
boolean gameOver = false;
//Ask the Hi-Lo question - pick number 1-100 (inclusive)
//Provide feedback answer too high, too low or you win!
//Limit number of tries in the game to 5
while (guess != answer) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
counter++;
if (guess < answer) {
System.out.println("Your guess " + guess + " is too low. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess > answer) {
System.out.println("Your guess " + guess + " is too high. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess == answer) {
System.out.println("Your guess " + guess + " is correct! You win!");
System.out.println();
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
}
if (counter ==6) {
System.out.println("Sorry, you've reached your max atttempts.");
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
// Play again logic
boolean isValid;
do {
System.out.print("Would you like to play again (Y/N)?");
playAgain = input.next().toUpperCase();
isValid = playAgain.equals("Y") || playAgain.equals("N");
playAgain = input.next();
counter = 1;
if ( !isValid ) {
System.out.println("Error, please enter Y or N");
System.out.println();
}
} while (!isValid);
}
}
You can add an extra condition to your while-loop:
while (guess != answer && counter < 5) {
// ...
}
Alternatively, you can break the loop when you get a right answer:
while (counter < 5) {
// ...
if (answer == guess){
// ...
break;
}
}

How to fix the replay function in this code?

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.

logical error with random number guessing game

In this program, the computer generates a random number (between 1-100) and the user attempts to guess it.
Runs until the user correctly guesses the number. Needs to print out the total number of tries it took before the number was guessed correctly.
Program runs fine, but there is a logical error. Nothing prints out when I correctly guess the number; the program just stops instead.
import java.util.*;
public class Problem3 {
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
int num = rand.nextInt(100)+1;
System.out.println(num); //prints out the random number so I know test works correctly
int count = 0;
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
console = new Scanner(System.in);
int guess = console.nextInt();
while(guess != num){ //while guess is not = to number
if(guess < num){ //if less than num
System.out.println("Your guess is too low");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else if( guess > num){ //if greater than num
System.out.println("Your guess is too high");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else{
count++;
System.out.println("You guessed correctly after " + count + " tries!");
}
}
}
}
Actually you never enter the else stage, because when the number is guessed, the while code won't execute and therefore the else code will never execute. So after that the number is guessed, so condition is false, exit while loop and System.out.print the Congrats message
Put this outside your while loop "at the end":
System.out.println("You guessed correctly after " + count + " tries!");
Here's what your code should look like:
while(guess != num){ //while guess is not = to number
if(guess < num){ //if less than num
System.out.println("Your guess is too low");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else{ //if greater than num
System.out.println("Your guess is too high");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}
}
System.out.println("You guessed correctly after " + ++count + " tries!");
Your while loop condition becomes false when the correct number is guessed. This makes the else unreachable.
EDIT
Here is how I would have tackled your problem. If you find yourself repeating code, it usually means there is an opportunity for improvement. Not only is there less code, but it is easier to read and follow what is going on. I'm not trying to steal the answer (#AmirBawab found the issue first), but I am a big believer in not just making code that works, but code that can be maintained and read by others. Hopefully as you continue learning you will keep that in mind. Happy coding!
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
int num = rand.nextInt(100) + 1;
int count = 0;
while (true) {
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
int guess = console.nextInt();
count++;
if (guess < num) {
System.out.println("Your guess is too low");
} else if (guess > num) {
System.out.println("Your guess is too high");
} else {
System.out.println("You guessed correctly after " + count + " tries!");
break;
}
}
console.close();
}

Categories