I can't seem to be able have my program ask the user if they would like to play again. The program ends when asking if they would like to continue. I added a break because before the program was continuously looping the correct answer and number of tries.
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
boolean play = true;
Scanner input = new Scanner(System.in);
Random Number = new Random();
int GuessNumber = 1+ Number.nextInt(1000);
int guess = 0;
int Tries = 0;
while(play) {
while(guess != GuessNumber) {
System.out.println("Please Enter a number between 1 and 1000:");
guess = input.nextInt();
Tries++;
if(guess == GuessNumber) {
System.out.println("You Win!");
break;
}
else if(guess < GuessNumber) {
System.out.println("Guess is too low");
}
else if(guess > GuessNumber) {
System.out.println("Guess is too high");
}
}
System.out.printf("Number was: %d",GuessNumber);
System.out.println("");
System.out.printf("Number of tries was: %d ",Tries);
System.out.println("");
System.out.println("Would you like to play again?(Yes/No)");
String playagain = input.nextLine();
if("Yes".equals(playagain))
play = true;
else
play = false;
}
}
}
A few things with your program.
As the comments have noted, you do need to flush your new-line character after using nextInt().
But, you must also set the guess value and try-count back to 0 after the user states that they would like to play again -- otherwise the program will just continue in a "You win!" loop.
I would recommend moving your variable declarations to the outer loop:
while(play) {
int guess = 0;
int guessNumber = 1 + Number.nextInt(1000);
int tries = 0;
...
}
Related
I am still new to Java and as such I am still figuring some things out. I have been having issues with including code asking the user if they want to play again. I have attempted putting it in the main class in a print statement which gave me an error. After that, I attempted putting it in the Guess.java class in multpile places but I just recieved errors. I have read up on the issue and some sites have suggested a while loop but I am unsure how to implement it into my current code. I have included both the main class which is called GuessingGame.java and the Guess.java class below. Thank you for any assistance that can be provided.
GuessingGame.java
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while (!win) {
System.out.println("You are limited to ten attempts."
+ " Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number"
+ " was: " + answer);
System.out.println("Do you want to play again?: ");
return;
}
if (guess > 1000) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount - 1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount - 1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " + answer);
System.out.println("It took you " + tries + " tries");
}
}
You already found a good position for adding this functionality:
System.out.println("Do you want to play again?: ");
The first step now is to also tell the user what he/she should enter after that question:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
After that we need to get the user input of course:
int number;
//If the user enters e.g. a string instead of a number, the InputMismatchException
//will be thrown and the catch-block will be executed
try {
number = input.nextInt();
//If number < 0 OR number > 1
if(number < 0 || number > 1) {
//The rest of the try-block will not be executed.
//Instead, the following catch-block will be executed.
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
//Clears the scanner to wait for the next number
//This is needed if the user enters a string instead of a number
input.nextLine();
}
If you don't know about try-catch-statements yet, I suggest to read this explanation. For details about the InputMismatchException, please see the documentation.
The problem now is that the user only has one chance to enter 0 or 1. If the user makes a wrong input the program will just stop. One solution to this problem is to just put the code in a while-loop:
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
After this block, we can be sure that number is either 0 or 1. So now we can add a simple if-statement to check the value:
if(number == 0) {
new Guess().doGuess();
}
return;
So all in all the code looks like this:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
if(number == 0) {
new Guess().doGuess();
}
return;
Don't forget to add the following import-statements:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
Try this. Basically, if the user responds with "yes" , we will call the function again.
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number" + " was: " + answer);
System.out.println("Do you want to play again? (yes/no): "); // modified line
if("yes".equalsIgnoreCase(input.next())){ // newly added if block
answer = generateRandomNumber();
tries=0;
i=0;
win = false;
doGuess();
}
return;
}
I am new to coding. I created a guessing game, and it works well but, I would like to know how to make it so that after the user attempts guessing the number 3 times, they get a hint which I put on the last line, but it is currently unreachable, and I do not know how to make the statement reachable, and in the do while loop. I am currently stuck. Thank you
import java.util.Scanner;
public class guessing_game {
public static void main (String[] args) {
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc() {
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
public static int run(Scanner kb) {
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
int num = 44;
int tries = 0;
do {
if (guess < num) {
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
run(kb);
}
else if ((guess > 100) || (guess < 0)) {
System.out.println("That isn't between 1-100 is it?");
System.out.println();
run(kb);
}
else if (guess > num) {
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
run(kb);
}
else if(guess == num) {
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y")) {
run(kb);
}
else if (choice.equalsIgnoreCase("n")) {
System.exit(0);
}
}
tries++;
}while(tries < 3);
{
System.out.print("Here's a hint the lucky number is 4");
}
return guess;
}
}
There are a few flow issues with your program, but here is a simple way to fix it up.
First of all, you are not actually using the value of guess when you return it from your run() method, so that can be removed.
Also, in cases like this, you would not want to use a do/while loop, but just while. You want to keep repeating the prompt until the user guesses correctly. So add a boolean to allow you to check if they won:
boolean correct = false; - We set it false to begin because they haven't won yet.
Now, instead of calling run() again after every guess (which resets the tries count every time, just let the while loop do its job and repeat itself. Hence, we need to move the prompt input into the while loop.
Here is a complete code listing of the changes:
import java.util.Scanner;
public class guessing_game {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc() {
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
// Change the return type to void as you never use the value returned
public static void run(Scanner kb) {
int num = 44;
// Add a boolean to determine if the game is won
boolean correct = false;
int tries = 0;
while (!correct) {
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
if (guess < num) {
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
} else if ((guess > 100) || (guess < 0)) {
System.out.println("That isn't between 1-100 is it?");
System.out.println();
} else if (guess > num) {
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
} else if (guess == num) {
// Flag the guess as correct; this will exit the loop after this run
correct = true;
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y")) {
run(kb);
} else if (choice.equalsIgnoreCase("n")) {
System.exit(0);
}
}
tries++;
}
}
}
1.You are recursively calling run() method and every time you call this method, a new variable try will be created and initialised to zero.
2. Your recursive call is before the condition check and due to the same reason the logic may never reach the condition check.
To make this work with minimal changes, you can use the following code. But this is not the best as it does not resolve the above shortcomings
import java.util.Scanner;
public class guessing_game {
static int tries = 0;
public static void main (String[] args)
{
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc()
{
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
public static int run(Scanner kb)
{
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
int num = 44;
do{
tries++;
if(tries>=3) break;
if (guess < num)
{
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
run(kb);
}
else if ((guess > 100) || (guess < 0))
{
System.out.println("That isn't between 1-100 is it?");
System.out.println();
run(kb);
}
else if (guess > num)
{
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
run(kb);
}
else if(guess == num)
{
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y"))
{
run(kb);
}
else if (choice.equalsIgnoreCase("n"))
{
System.exit(0);
}
}
}while( tries < 3);
{
System.out.print("Here's a hint the lucky number is 4");
}
return guess;
}
}
When I compile, that try to enter (y) to play again my do - while is not working, it takes me out of the loop.
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
int guessNumber = 0;
do
{
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
}
Change the code as below: (You just need to update the variables inside the loop)
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = 0;
int guessNumber = 0;
do
{
// new lines to be added
theNumber = (int)(Math.random() * 100 + 1);
guessNumber = 0;
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
Here is the execution of code on Jshell:
The reason the program is not working is because the do-while loop does one iteration before it gets to the "while" part. In your case, the program successfully finishes the loop after a user correctly guesses the number. Your program breaks because after that you are requiring the user to enter 'y' to continue endlessly without letting them guess a number. If they guess a number, the program terminates.
I am having a few issues,
I am having issues getting my program to actually end.
I can't figure out when I prompt the user to play again how to initiate a new game.
Any guidance would be appreciated.
Thanks
import java.util.*;
public class HiLowGuessingGame {
public static void main(String[] args) {
// Creates a random number generator
Random random= new Random();
// For getting input from the user
Scanner sc = new Scanner(System.in);
int number = random.nextInt(100);
int guess = +1;
//Counts the number of guesses
int guesscount = 0;
guesscount ++;
//Allows user to quit the game
String input;
int quit = 0;
String playagain;
String y="y";
String n="n";
// Prompts user for their next guess
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
// Loop until the user guesses correctly
while (true){
// Reads the next guess
guess = sc.nextInt();
//If guess it to low or high
if (guess == quit){
System.out.println("Game Over!");}
else if (guess < number ){
System.out.println("Guess is too low, please try again");
guesscount ++; }
else if(guess > number ){
System.out.println("Guess is too high, please try again");
guesscount ++; }
// Correct guess and number of guesses
else {
System.out.println("Your guess is correct = " + number + "\n" +"Number of Guesses = " +guesscount );
while (true) {
// Play again?
boolean isplayagain = true;
while (true) {
System.out.println("play another game?(y/n)");
String playagainResponse = sc.next();
if (playagainResponse.equalsIgnoreCase("y")) {
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
guess = sc.nextInt();
break;
} else if (playagainResponse.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
isplayagain = false;
break;
}
}
if (!isplayagain) {
break;
}
}
}
}
}
}
I ran your code, and I noticed that you use break statements to exit out of the for loops, but you never break out of the outermost for loop, so the game never actually ends.
In this case however, I would recommend not using break and use System.exit(0), which will end the game normally. I'll add a reference link at the bottom. This should fix your issue of the game not ending.
As for your other problem, I'm not sure what you mean. Do you mean that it doesn't restart a new game properly? The random number is only issued at the start of the program, so when a new game is started, the random number stays the same. Also, the guess count isn't reset with a new game. I would just put all the code which resets the variables in the if-statement responsible for starting a new game.
Good luck!
https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit(int)
I changed your program a bit to do what you want.
If i get what you are trying to do i think this is the code for this.
import java.util.*;
public class HiLowGuessingGame {
public static void main(String[] args) {
// Creates a random number generator
Random random= new Random();
// For getting input from the user
Scanner sc = new Scanner(System.in);
int number = random.nextInt(100);
int guess = +1;
//Counts the number of guesses
int guesscount = 0;
guesscount ++;
//Allows user to quit the game
String input;
int quit = 0;
String playagain;
String y="y";
String n="n";
boolean isplayagain = false;
// Prompts user for their next guess
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
// Loop until the user guesses correctly
while (true){
// Reads the next guess
guess = sc.nextInt();
//If guess it to low or high
if (guess == quit){
System.out.println("Game Over!");
break;}
else if (guess < number ){
System.out.println("Guess is too low, please try again");
guesscount ++; }
else if(guess > number ){
System.out.println("Guess is too high, please try again");
guesscount ++; }
// Correct guess and number of guesses
else {
System.out.println("Your guess is correct = " + number + "\n" +"Number of Guesses = " +guesscount );
// while (true) {
// Play again?
while (true) {
System.out.println("play another game?(y/n)");
String playagainResponse = sc.next();
if (playagainResponse.equalsIgnoreCase("y")) {
System.out.println("New game starts now!");
isplayagain=true;
break;
} else if (playagainResponse.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
isplayagain = false;
break;
}
}
if (!isplayagain)break;//cause of the program to not end if user gives n
}
if(isplayagain){
number = random.nextInt(100);
guesscount=0;
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
isplayagain=false;}
}
}
}
I'm working on this guessing game for school. I've realized that at some point I deleted my while loop for the user's guess equalling the computer's random number and it has messed up the results of my program. I thought that I could just add a nested while loop, but that hasn't worked. I've been trying to figure this out for hours.
Any ideas how to add something like while (guess == number) to my code and keep it working?
/*
Programming Assignment #3: Guess
Peter Harmazinski
Week 8
Guessing Game
*/
import java.util.*;
public class Guess {
public static final int RANGE = 100;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
boolean again = true;
double guessesDividedByGames = 0;
int maxGuesses = 0;
int numGames = 0;
int numGuesses = 1;
int totalGuesses = 0;
Random rand = new Random();
int number = rand.nextInt(RANGE) + 1;
int guessTracker = 0;
while(again) {
getInstructions();
int guess = getGuess(console);
numGuesses = getHigherLower(guess, number, console);
totalGuesses += numGuesses;
again = playAgain(numGuesses, console);
numGames++;
if (numGuesses > maxGuesses) {
maxGuesses = numGuesses;
}
}
guessesDividedByGames = (double)totalGuesses / numGames;
getResults(numGames, totalGuesses, guessesDividedByGames, maxGuesses);
}
//Prints instructions for user
public static void getInstructions() {
System.out.println("This program allows you to play a guessing game");
System.out.println("I will think of a number between 1 and " + RANGE);
System.out.println("and will allow you to guess until you get it.");
System.out.println("For each guess, I will tell you whether the");
System.out.println("right answer is higher or lower than your guess");
System.out.println("");
}
//Allows the user to play again if first letter of input is "y" or "Y"
public static boolean playAgain(int guessesNum, Scanner console) {
boolean anotherTime = false;
System.out.println("You got it right in " + guessesNum + " guesses.");
System.out.println("");
System.out.print("Do you want to play again? ");
String repeat = console.next();
String[] yesOrNo = repeat.split("");
System.out.println("");
if (yesOrNo[0].equals("y") || yesOrNo[0].equals("Y")) {
anotherTime = true;
}
return anotherTime;
}
//Outputs the results if the user doesn't play again
public static void getResults(int gamesTotal, int guessesTotal, double guessesDividedByGames, int guessesMax) {
System.out.println("Overall results:");
System.out.println("\ttotal games\t= " + gamesTotal);
System.out.println("\ttotal guesses\t= " + guessesTotal);
System.out.println("\tguesses/game\t= " + guessesDividedByGames);
System.out.println("\tmax guesses\t= " + guessesMax);
}
//Tells the user whether the random number is higher or lower
//and then returns the number of guesses
public static int getHigherLower(int guess, int randomNumber, Scanner console) {
int guessIncreaser = 1;
while (guess > randomNumber) {
System.out.println("lower");
guess = getGuess(console);
guessIncreaser++;
}
while (guess < randomNumber) {
System.out.println("higher");
guess = getGuess(console);
guessIncreaser++;
}
return guessIncreaser;
}
//Asks the user to guess the random number
//then returns the guess
public static int getGuess(Scanner console) {
System.out.println("I'm thinking of a number...");
System.out.print("Your Guess? ");
int playerGuess = console.nextInt();
while (playerGuess < 1 || playerGuess > RANGE) {
System.out.println("Out of range, please try again.");
System.out.print("Your Guess? ");
playerGuess = console.nextInt();
}
return playerGuess;
}
}
The problem appears to be your getHigherLower method, specifically these two while blocks:
while (guess > randomNumber) {
System.out.println("lower");
guess = getGuess(console);
guessIncreaser++;
}
while (guess < randomNumber) {
System.out.println("higher");
guess = getGuess(console);
guessIncreaser++;
}
If the user guessed a number lower than randomNumber, then higher, both while blocks would be escaped. Instead, what you want is this:
while (guess != randomNumber) {
if (guess > randomNumber) {
System.out.println("lower");
}
else {
System.out.println("higher");
}
guess = getGuess(console);
guessIncreaser++;
}
What you need is one big while loop not two little ones
while (guess != randomNumber) {
if (guess > randomNumber) {
System.out.println("lower");
} else {
System.out.println("higher");
}
guess = getGuess(console);
guessIncreaser++;
}
First off, I'm hesitant to just give you the answer in code since this is for a school project and we learn by challenging ourselves and actualizing solutions. But I'm willing to point you in the right direction.
1. getHigherLower()
As others have pointed out, your two while loops are set up to cause errors. For instance, if I first guess too low, and then too high, your method mistakenly tells me I guessed correctly. This is a big problem!
Random number = 63
Guess 1 = 34 (lower)
Guess 2 = 100 (higher)
Actually your program tells me my guess of "100" when the number is "63" is correct!
// 1st conditional check: 34 !> 63, so skips first while loop
while (guess > randomNumber) {
guess = getGuess(console);
}
// 1st conditional check: 34 < 63, so enters second while loop
// 2nd conditional check: 100 !< 63, so skips second while loop
while (guess < randomNumber) {
// guess now becomes 100, goes back to top of while loop to check condition again
guess = getGuess(console);
}
// returns and exits method here (program wrongly thinks user has guessed correctly!)
Note that you can do a
System.out.println("random number: " + number);
to test that you're actually guessing the random number correctly. You might look into some JUnit testing as well.
James Ko seems to have a good feel for a better method implementation.
2. playAgain()
You use an if statement to check if the first index in an array of strings equals "y" or "Y" but your program never continues. Why is this?
if (yesOrNo[?].equals("y") {
anotherTime = true;
}
You should consider whether user input is really being placed at the first index or not?
Hint: loop through the "yesOrNo" array and print out each index to see where the user input is being placed in the array.
for (int i = 0; i < yesOrNo.length; i++) {
System.out.println("String at index " + i + ": " + yesOrNo[i]);
}
Good luck and remember that testing is your friend!