I'm having an issue with my code where the program will not play again, but
also will not end.
The code continues to loop in the inner while loop after a win or too many guesses.
Here is my code:
/**
* This program will prompt the user to guess a secret number
* This number will is between 1 and N, where N is a postive number
*
* #author: Perry Chapman
*/
import java.util.Scanner;
public class SecretNumber2
{
public static void main( String [] args )
{
int N;
int randomNumber;
int guess;
int tries, maxTries;
boolean win = false;
boolean playing = true;
int playAgain = 1;
tries = 0;
while(playing == true)
{
Scanner input = new Scanner( System.in );
System.out.println( "This is a guessing game." );
System.out.println( "What is the max number of tries: ");
maxTries = input.nextInt();
System.out.println( "Enter a value between 1 and 1000: " );
N = input.nextInt();
randomNumber = (int)(N * Math.random()) + 1;
while (win == false)
{
System.out.println( "Enter your guess: " );
guess = input.nextInt();
tries++;
if (guess == randomNumber)
{
System.out.println( "Congratulations! The number of guesses it took you was " + tries );
win = true;
System.out.println("Would you like to play again? \n (1)Yes or (2)No: ");
playAgain = input.nextInt();
if(playAgain == 1) {
playing = true;
}
else if (playAgain == 2) {
playing = false;
}
tries = 0;
}
else if(guess < randomNumber)
System.out.println( "Too low, guess again." );
else if(guess > randomNumber)
System.out.println( "Too high, guess again." );
else if(tries == maxTries)
{
System.out.println("You have exceeded the max number of tries. \nYou lose.");
System.out.println("\nWould you like to play again?\n (1)Yes or (2)No: ");
playAgain = input.nextInt();
if(playAgain == 1) {
playing = true;
}
else if(playAgain == 2) {
playing = false;
}
tries = 0;
}
}
}
}
}
Andrew is right, in order to loop the condition need to be true.The if else statement need to be in the right order. Here is a fix, I hope it will help.
public static void main(String[] args) {
int N;
int randomNumber;
int guess;
int tries, maxTries;
boolean lose;
boolean playing = true;
int playAgain;
tries = 0;
while (playing) {
Scanner input = new Scanner(System.in);
System.out.println("This is a guessing game.");
System.out.println("What is the max number of tries: ");
maxTries = input.nextInt();
System.out.println("Enter a value between 1 and 1000: ");
N = input.nextInt();
randomNumber = (int) (N * Math.random()) + 1;
lose = true;
while (lose) {
System.out.println("Enter your guess: ");
guess = input.nextInt();
tries++;
if (guess == randomNumber) {
System.out.println("Congratulations! The number of guesses it took you was " + tries);
lose = false;
System.out.println("Would you like to play again? \n (1)Yes or (2)No: ");
playAgain = input.nextInt();
if (playAgain == 1) {
playing = true;
} else if (playAgain == 2) {
playing = false;
}
tries = 0;
} else if (tries == maxTries) {
System.out.println("You have exceeded the max number of tries. \nYou lose.");
System.out.println("\nWould you like to play again?\n (1)Yes or (2)No: ");
playAgain = input.nextInt();
if (playAgain == 1) {
playing = true;
} else if (playAgain == 2) {
playing = false;
}
lose = false;
tries = 0;
} else if (guess < randomNumber) {
System.out.println("Too low, guess again.");
} else if (guess > randomNumber) {
System.out.println("Too high, guess again.");
}
}
}
}
I think you have two issues.
The first is that after successfully guessing the number you never set win back to false. So you won't ever enter the inner while loop a second time.
The second is the ordering of the if/else if statements, there is never a scenario where a guess can reach the final else if. Every situation will validate as true in one of the previous three ifs.
/**
* This program will prompt the user to guess a secret number
* This number will is between 1 and N, where N is a postive number
*
* #author: Perry C
*/
import java.util.Scanner;
public class SecretNumber
{
public static void main( String [] args )
{
int N;
int guess;
int playAgain;
int tries;
int maxTries;
playAgain = 1;
tries = 0;
Scanner input = new Scanner( System.in );
while(playAgain == 1)
{
boolean win = false;
System.out.println( "This is a guessing game." );
System.out.println( "How many guesses would you like?" );
maxTries = input.nextInt();
System.out.println( "Enter a value between 1 and 1000: " );
N = input.nextInt();
int randomNumber = (int)(N * Math.random()) + 1;
while (win == false)
{
System.out.println( "Enter your guess: " );
guess = input.nextInt();
tries++;
if(guess == randomNumber)
{
System.out.println( "Congratulations! The number of guesses it took you was \t" + tries );
win = true;
System.out.println( "Would you like to play again(1 or 2):" );
playAgain = input.nextInt();
tries = 0;
}
else if(guess < randomNumber)
System.out.println( "Too low, guess again." );
else if(guess > randomNumber)
System.out.println( "Too high, guess again." );
if(tries == maxTries)
{
System.out.println( "You have exceeded the max number of tries. \n You lose." );
System.out.println( "Would you like to play again(1 or 2):" );
playAgain = input.nextInt();
tries = 0;
win = true;
}
}
}
}
}
Found the issue, thought I would post the answer in case anyone else might stumble on this thread! Thanks for the help!
Related
So I've been working on this and it works fine, only problem is that after you guess a number that's not between 1 and 100, it goes onto the next guess when the try shouldn't count against you. I've attached a picture of what the output SHOULD look like.
Do I need a 'for' statement or a boolean variable?
And here is my code:
Random generator = new Random();
//import the scanner for prompt
Scanner input = new Scanner(System.in);
//integers for the secret number, input guess of the secret number, tries and limit to tries
int numberToGuess = 1 + generator.nextInt(100);
int numberOfTries = 1;
int limit = 10;
int guess;
//prompt user to enter a number to guess
System.out.println("You have 10 tries to guess a number between 1 and 100");
//start of while loop
while (numberOfTries <= 10) {
System.out.print("Guess number " + numberOfTries + ": ");
guess = input.nextInt();
//if else statements (outputs)
if (guess < numberToGuess)
System.out.println("Your guess is too low. Try again.");
else if (guess > 100)
System.out.println("Guesses should be between 1 and 100.");
else if (guess > numberToGuess)
System.out.println("Too high. Try again.");
else if (guess == numberToGuess) {
System.out.println("Congratulations! You have correctly guess the number in " + numberOfTries + " tries");
System.exit(0);
} else {
System.out.println("Sorry, you did not guess the guess the answer in 10 tries");
System.out.println("The number was " + numberToGuess);
//break to end while loop
break;
}
numberOfTries++;
// If statement after executing the while loop the output if user loses and answer to secret number
if (numberOfTries > 10) {
System.out.println("Sorry, you did not guess the guess the answer in 10 tries");
System.out.println("The number was " + numberToGuess);
}
}
Don't increment numberOfTries++; if they guess a number outside of the range. Put the increment inside the if statements
Try using a nested do-while loop inside your primary while loop:
//start of while loop
while(numberOfTries <= 10){
//get a valid guess
do{
boolean valid = true;
System.out.print("Guess number " + numberOfTries + ": ");
guess= input.nextInt();
//if else statements (outputs)
if (guess < numberToGuess){
System.out.println("Your guess is too low. Try again.");
valid = false;
}
else if (guess > 100){
System.out.println("Guesses should be between 1 and 100.");
valid = false;
}
while (!valid);
//handle the valid guess
}
Here's how I'd do it. You tell me which one you prefer:
import java.util.Random;
import java.util.Scanner;
/**
* Created by Michael
* Creation date 3/4/2016.
* #link https://stackoverflow.com/questions/35809392/while-loop-in-java-number-guess
*/
public class NumberGuess {
public static final int MIN_VALUE = 1;
public static final int MAX_VALUE = 100;
public static final int MAX_TRIES = 10;
public static void main(String[] args) {
Random generator = new Random();
Scanner input = new Scanner(System.in);
String playAgain;
do {
int answer = MIN_VALUE + generator.nextInt(MAX_VALUE);
System.out.println(String.format("You have %d tries to guess a number between %d and %d", MAX_TRIES, MIN_VALUE, MAX_VALUE));
boolean correct = playGuessingGame(input, answer);
if (!correct) {
System.out.println(String.format("The number was %d", answer));
}
System.out.print("Play again? [Y/N]: ");
playAgain = input.nextLine();
} while ("Y".equalsIgnoreCase(playAgain));
}
public static boolean playGuessingGame(Scanner input, int answer) {
boolean correct = false;
int numTries = 0;
do {
System.out.print(String.format("Guess %d: ", ++numTries));
int guess = Integer.parseInt(input.nextLine());
if (guess < MIN_VALUE) {
System.out.println(String.format("Guess %d is below minimum %d", guess, MIN_VALUE));
} else if (guess > MAX_VALUE) {
System.out.println(String.format("Guess %d is above maximum %d", guess, MAX_VALUE));
} else if (guess < answer) {
System.out.println(String.format("Guess %d is too low. Try again.", guess));
} else if (guess > answer) {
System.out.println(String.format("Guess %d is too high. Try again.", guess));
} else {
System.out.println("Woo hoo! You got it right!");
correct = true;
break;
}
} while (numTries < MAX_TRIES);
return correct;
}
}
You and your professor realize that it's almost impossible to lose this game. Right?
A bisection strategy says you can always get the right answer with 10 tries. Make that number smaller for a challenge.
increamenting should be done inside the if statemnt :D
I am writing a simple java guessing game, the game is supposed to randomly pick a number between 1 and 100 and then after you pick the correct number it asks you if you would like to play again. I know i should be able to use a Do while loop to ask if the user would like to play again, but every time I try I cannot make it work. This is my fully functional program without the do while loop. If someone could help me prompt the user if they would like to play again I would be very thankful. I am still very new to programming.
Also I apologize if the indenting isn't 100% correct.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame
{
public static void main (String [] args)
{
//Variables
Random randomNumber = new Random();
Scanner kbd = new Scanner(System.in);
int computerValue = randomNumber.nextInt(100);
int numberOfTries = 0;
int success = 0;
int guess = 0;
//Logic and While Loop
while (success ==0)
{
System.out.println("please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;
if (guess < 1 || guess > 100){
System.out.println("Invalid input");
}
else if (guess == computerValue){
success++;
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
}
else if (guess < computerValue){
System.out.println("Your guess is too low!");
}
else if (guess > computerValue){
System.out.println("Your guess is too high!");
}
}
}
}
Try this:
while(true) {
computerValue = randomNumber.nextInt(100);
numberOfTries = 0;
while (true) {
System.out.println("please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;
if (guess < 1 || guess > 100) System.out.println("Invalid input");
else if (guess == computerValue) {
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
// leave the first loop
break;
}
else if (guess < computerValue) System.out.println("Your guess is too low!");
else if (guess > computerValue) System.out.println("Your guess is too high!");
}
System.out.println("Do you want to play again? (1:Yes/2:No)");
// if input is not yes leave second loop
if(kbd.nextInt() != 1) break;
}
If you want to use a do while loop this would work.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
//Variables
Random randomNumber = new Random();
Scanner kbd = new Scanner(System.in);
int computerValue;
int numberOfTries = 0;
int success = 0;
int guess;
boolean playAgain;
//Logic and While Loop
do {
computerValue = randomNumber.nextInt(100);
guess = 0;
playAgain = false;
while (guess != computerValue) {
System.out.println("Please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;
if (guess < 1 || guess > 100) {
System.out.println("Invalid input");
} else if (guess < computerValue) {
System.out.println("Your guess is too low!");
} else if (guess > computerValue) {
System.out.println("Your guess is too high!");
}
}
success++;
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
System.out.println("Would you like to play again?");
switch (kbd.next()) {
case "yes":
playAgain = true;
break;
default:
break;
}
} while (playAgain);
System.out.println("Goodbye");
}
}
Prompt the user if he wants to play again at
else if (guess == computerValue) {
success++;
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
}
If the user inputs yes success--;
i'm currently trying to create a while loop for my program, a Guessing game. I've set it up so the user can create a max value i.e 1-500 and then the user can proceed to guess the number. When the number has been guessed, the User can press 1, to close, anything else to continue running the loop again.
My problem, is that the code gives me an error when trying to continue the loop, no compiling errros
This is my Code:
import java.util.Random;
import java.util.Scanner;
public class Gættespil2
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Indsæt loftets højeste værdi : ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
while (win == false)
{
System.out.println(" Gæt et tal mellem 1 og "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Koldere, gæt igen");
}
else if (guess > TAL) {
System.out.println("Varmere, Gæt igen!!");
}
}
System.out.println(" Tillykke du vandt...endeligt!!! ");
System.out.println(" tallet var" + TAL);
System.out.println(" du brugte " + FORSØG + " forsøg");
System.out.println("Slut spillet? tast 1.");
System.out.println("tryk på hvadsomhelst for at spille videre");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Simple answer. You didn't initialize all the necessary values within your 'keepPlaying' loop before beginning a second round after the player successfully completed the first round. See annotations to your code, below:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Enter a maximum limit: ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
// *** LOOK HERE ***
// Reset the 'win' flag here, otherwise the player receives an
// automatic win on all subsequent rounds following the first
win = false;
while (win == false)
{
System.out.println("Guess the number between one and "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Colder, guess again!");
}
else if (guess > TAL) {
System.out.println("Warmer, guess again!");
}
}
System.out.println("You've found the number!");
System.out.println("The number was: " + TAL + ".");
System.out.println("You guessed " + FORSØG + " times.");
System.out.println("To quit, enter 1.");
System.out.println("Provide any other input to play again.");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Sorry for the translation into English -- I had to make sure I was reading things correctly. You might also want to substitute "higher" and "lower" for "warmer" and "colder." "Warmer" and "colder" tend to suggest a proximity to the correct answer, as opposed to the direction in which that correct answer lies.
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.
What I really am stuck with is the second to last variable userGuessDifference. It remains at zero making my second while loop not run properly as it just keeps going back to the first else if statement.
public class GuessingGame {
/**
* #param args
*/
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
int userGuessDifference = (Math.abs(correctAnswer) - Math.abs(userGuess));
boolean flag = false;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10)
{
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
}
else if (difficulty == 25)
{
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
}
else if (difficulty == 50)
{
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
}
else
{
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (!flag || (counter <= guesses))
{
if (userGuess == correctAnswer)
{
System.out.println("CONGRATS YOU WIN!");
flag = true;
}
else if ((userGuessDifference <= (difficulty * .10)))
{
System.out.println("HOT!");
userGuess = keyboard.nextInt();
counter++;
}
else if ((userGuessDifference < (difficulty * .25)) && (userGuessDifference > (difficulty * .10)))
{
System.out.println("Warm...");
userGuess = keyboard.nextInt();
counter++;
}
else
{
System.out.println("Ice cold.");
userGuess = keyboard.nextInt();
counter++;
}
}
}
}
As #SotiriosDelimanolis wrote, you never reassign userGuessDifference. This should be done inside the while loop.
Moreover, there is another problem with your code: if you guess the number, the program just prints "CONGRATS YOU WIN!" forever, but it seems to me that you wanted to quit from the while loop once the user guesses the number (I guess the flag variable was introduced for this reason).
I slightly changed your code in order to meet this requirement:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10) {
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
} else if (difficulty == 25) {
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
} else if (difficulty == 50) {
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
} else {
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (counter <= guesses) {
// int userGuessDifference = (Math.abs(correctAnswer) - Math
// .abs(userGuess));
int userGuessDifference = Math.abs(correctAnswer - userGuess);
if (userGuess == correctAnswer) {
System.out.println("CONGRATS YOU WIN!");
break;
}
else if ((userGuessDifference <= (difficulty * .10))) {
System.out.println("HOT!");
}
else if ((userGuessDifference < (difficulty * .25))
&& (userGuessDifference > (difficulty * .10))) {
System.out.println("Warm...");
}
else {
System.out.println("Ice cold.");
}
userGuess = keyboard.nextInt();
counter++;
}
}
}