my goal in the following code is to keep getting guesses until the user either guesses the right number, or quit. To quit, I am able to easily break out of my loops, but when I try to continue in my loops, it doesn't work right. First it requires multiple inputs, and then also entirely regenerates my number, while what I want to do is to keep getting guesses (asking user) for the SAME random number.
Below is my code:
public class Test {
public static void main(String[] args) {
int count, randNum, guess;
count = 0;
Scanner scan = new Scanner(System.in);
while (true) {
Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");
guess = scan.nextInt();
count += 1;
if (guess == randNum) {
System.out.println("Correct guess.");
System.out.println("It took " + count + " tries to guess the right number");
System.out.println("Would you like to play again? ");
System.out.println("Press any letter to play again or q to quit: ");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else{
continue;
}
}
if (guess > randNum) {
System.out.println("Your guess is bigger than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
else if (guess < randNum) {
System.out.println("Your guess is smaller than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
}
}
}
The code for generating the random number should be before the while statement. When you call continue, it goes back to the first line of the while block and consequently generates another random number.
Your statement declaring the int randNum is inside of the while loop, so every time the while loop repeats, the number is declared (again) and set to a value between 1 and 100.
If you want to prevent this, declare the variable and initialize it with a random value outside of the while loop.
A small side note: by initializing the variable inside of the while loop, you are limiting its scope more than you probably want to. Every time it loops through, the previous randNum you created no longer exists, and it then creates a new one. Basically, if you want it to be more permanent, initialize it outside of the loop.
Also, if you only want it to ask for a number between 1 and 100 the very first time, move it outside of the loop. This however is up to you on whether or not you want it to ask each time, or just once.
//…
public static void main(String[] args) {
int count, randNum, guess;
count = 0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");
while (true) {
/*Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");*/
guess = scan.nextInt();
count += 1;
//…
Related
Create a program that randomly generates a number from 1-100 and asks the user to guess it. If the number the user inputs is to low or to high display a message to tell them so. When the user guesses the random number tell the user how much tries it took him to get that number. After that ask the user if they want to do it again if the user does repeat the process with a new random number generated.
The problem is that I can't seem to figure out how to let the user do it again, it seems to display an error in code when I run the program. If anyone can help me with this issue that would be great. Thank you!
import java.util.Scanner;
import java.util.Random;
public class RandomGuess
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
Random randy = new Random();
//#declaring variables
int num, count = 0;
final int random = randy.nextInt(100);
String input;
char yn;
//#random number
System.out.println("Num = " + random);
//#title or header
System.out.println("Random Number Guessing Game");
System.out.println("===========================");
//#asking user for input
do
{
System.out.print("Guess the random number " +
"from 1 to 100===> ");
num = keyboard.nextInt();
//#if the number the user entered
//#was less than the random number
if(num < random)
{
//#display this message
System.out.println("Your guess is too low try again...");
System.out.println();
}
//#if the number the user entered
//#was less than the random number
if(num > random)
{
//#display this message
System.out.println("Your guess is too high try again...");
System.out.println();
}
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
}
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y');
}
while (num > 1 || num > 100);
}
}
There are a couple of problems with your code without even seeing the error that is displayed (I've put comments in those areas):
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
} // You should put an else here
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y'); // This will keep asking if you want to try again so long as you enter a "y"
// But it won't actually let you try.
// Why? Because if you enter a y" it will loop back to the question.
}
while (num > 1 || num > 100); // This should probably be (random != num)
}
}
Here is a revised version
count++;
if (num == random) {
System.out.println("You guessed the random number in " +
count + " guesses!");
} else {
yn = 'x'; // can be anything other than y or n
while(yn != 'y' && yn != 'n') {
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.toLowerCase().charAt(0);
}
}
}
while (num != random && yn == 'y');
}
}
Hopefully this is enough to move you forward.
Also, please post the error message and/or a description of what it is doing wrong along with a description as to what you actually wnt it to do.
As for the exception, the problem is that scanner.nextInt does not consume the newline at the end of the numbe you entered. So, your "continue Y/N" question gets what's left over from the previous line (i.e. a new line => an empty string).
You could try this:
num = -1; // Initialise the number to enable the loop
while (num <= 1 || num >= 100) {
System.out.print("Guess the random number from 1 to 100===> ");
String ans = keyboard.nextline();
try {
num = Integer.parseInt(); // Convert the string to an integer - if possible
} catch (NumberFormatException e) {
// If the user's input can not be converted to an integer, we will end up here and display an error message.
System.out.println ("Please enter an integer");
}
}
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!
I have created a game where the user guesses a random number that was created 0-100. If their guess is too high, the system tells them to guess higher, and the same for if their guess is lower than the actual number. However, I need to initialize each guess to an array, in the order that they inputted. I know how to initialize an array, but I need help on storing the player's guesses into the array. Here is my code, and any help/advice is appreciated!
public static void randomNumGame(){
// begin of method
Scanner numbers = new Scanner(System.in);
Random randomGenerator = new Random();
int[] guess;
guess = new int[6];
guess[0]=0;
guess[1]=0;
guess[2]=0;
guess[3]=0;
guess[4]=0;
guess[5]=0;
System.out.println("running ...");
int thisRandomInt = randomGenerator.nextInt(100);
int attempt = 0;
boolean done = false;
while(!done){
System.out.print("Guess a number from 0 to 100 : ");
int myGuess = numbers.nextInt();
attempt++;
if(myGuess == thisRandomInt && attempt <= guess.length){
done = true;
System.out.println("You won. It took " + attempt+ " times to guess my number.");
}else if (attempt >= guess.length){
System.out.println("Game Over. My number is "+thisRandomInt );
done = true;
}else if (myGuess < thisRandomInt){
System.out.println("Guess a higher number");
}else{
System.out.println("Guess a lower number");
}
}
}// end of method
if(myGuess == thisRandomInt && attempt <= guess.length){
done = true;
System.out.println("You won. It took " + attempt+ " times to guess my number.");
}else if (attempt >= guess.length){
System.out.println("Game Over. My number is "+thisRandomInt );
done = true;
}else if (myGuess < thisRandomInt){
guess[attempt-1] = myGuess;
System.out.println("Guess a higher number");
}else{
guess[attempt-1] = myGuess;
System.out.println("Guess a lower number");
}
You don't need to explicitly init your quest array with zeroes. Apart from that, you can do something like this:
System.out.print("Guess a number from 0 to 100 : ");
int myGuess = numbers.nextInt();
guess[attempt++] = myGuess;
Also, instead of the done flag, you can call break instead of declaring the flag true - it will escape the loop.
I need to create a simple game where a random number is created, and the user has to guess the number by inputting numbers into a scanner. If their guess is too high, the system tells them to guess lower, and the same if it is too low.
I'm using a while loop, but I don't know how to continuously call the scanner so that the user can keep guessing. Here is my code so far:
public static void highLow()
{
Random randomGenerator = new Random();
int num = randomGenerator.nextInt(100);
boolean loop = true;
while(loop)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a number: ");
int numGuess = scanner.nextInt();
if (numGuess > num)
System.out.println("Guess lower!");
scanner.nextInt();
if (numGuess < num)
System.out.println("Guess higher!");
scanner.nextInt();
if (numGuess == num)
System.out.println("Correct! You win!!!");
loop = false;
}
}
You're almost there. Here are some suggestions:
Assign the input of the Scanner back into numGuess in order to have the value "ready" for the next loop iteration.
Use braces after your if conditions.
You don't have to redeclare the Scanner object each time. Do it once, before the loop.
It was a combination of #1 and #2 that was causing your code to fail before. Look closely at your if blocks. If you leave off the braces, only the first line following is part of the if. (see Is it ok if I omit curly braces in Java?)
So, you meant this:
if (numGuess == num)
System.out.println("Correct! You win!!!");
loop = false;
But what the compiler "saw" was really this:
if (numGuess == num)
System.out.println("Correct! You win!!!");
loop = false;
The misplaced loop = false will ensure that your loop only ever runs once, no matter what the user entered. Explicitly including braces keeps it unambiguous!
Here's what your code looks like after making the above changes:
public static void highLow()
{
Random randomGenerator = new Random();
int num = randomGenerator.nextInt(100);
boolean loop = true;
Scanner scanner = new Scanner(System.in);
int numGuess = 0;
while(loop)
{
System.out.print("Please enter a number: ");
numGuess = scanner.nextInt();
if (numGuess > num) {
System.out.println("Guess lower!");
numGuess = scanner.nextInt();
} else if (numGuess < num) {
System.out.println("Guess higher!");
numGuess = scanner.nextInt();
} else if (numGuess == num) {
System.out.println("Correct! You win!!!");
loop = false;
}
}
}