Scanner inside while loop - java

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;
}
}
}

Related

Why is my do-while loop not working?

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.

unable to re-loop through a while loop successfully

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;
//…

Ending and restarting a program from user input

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;}
}
}
}

Play Again feature not working

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

initializing scanner values in a loop to an array

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.

Categories

Resources