My Goal: To make a program that can check if the number you guessed is correct. It will tell you if it's too high/low. It needs to continue giving you chances until you guess correctly. Also, it needs to be able to resume from the start after you finish if you want to.
Problem: My if statements are stuck in an infinite loop, and attempting to restart the program at the end does not work at all.
import java.util.Random;
import java.util.Scanner;
public class driver {
public static void main (String [] args) {
// Output number of guesses.
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100) + 1;
System.out.println(randomInt);
System.out.println("Welcome to my guessing game. What is your first guess that is between 1 and 100?");
int userInput = scan.nextInt();
String playAgain = "Y";
int guesses = 0;
System.out.println(randomInt);
while (playAgain == "Y") {
if (userInput > 0 && userInput < 100) {
if (userInput == randomInt){
guesses++;
System.out.println ("Right! Guesses: " + guesses);
playAgain = "f";
}
// Too low
else if (userInput < randomInt) {
guesses++;
System.out.println ("Your guess was too LOW.");
}
// Too high
else {
System.out.println ("Your guess was too HIGH.");
guesses++;
}
}
}
// I want to be able to resume from the top if the user says Y.
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
}
The last two lines should be inside your while loop, the problem is with your braces
while (playAgain == "Y") {
if (userInput > 0 && userInput < 100) {
if (userInput == randomInt){
guesses++;
System.out.println ("Right! Guesses: " + guesses);
playAgain = "f";
}
else if (userInput < randomInt) {
guesses++;
System.out.println ("Your guess was too LOW.");
}
else {
System.out.println ("Your guess was too HIGH.");
guesses++;
}
}
}
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
The bottom part should look like:
guesses++;
}
}
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
}
The way it was means that the condition of your while is never updated. I assume you want it to update after each input from the user.
Related
I have written the code below. I have run the program and it allows the user to guess the correct number and return the message successfully. However, I couldn't get it to regenerate a new random number? I also couldn't include an option to ask whether the user wants to quit or not. Please help. Thank you.
import java.util.*;
class CompterAge {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
boolean correctGuess = false;
Random r = new Random();
int randNum = r.nextInt(100-1+1) + 1;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input == "Yes") {
correctGuess = false;
} else {
break;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
}
This code works, I have added another flag variable and corrected some logical errors. See the comments.
boolean correctGuess = false;
boolean endGame = false;
Random r = new Random();
while (!endGame){
int randNum = r.nextInt(101); //Why did you have (100-1+1) + 1 ?? Simple (101) was enough
correctGuess = false;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
correctGuess = true; //Will exit the Inner Loop
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next().toLowerCase();
if (input.equals("yes")) { //You can not use == for String Comparisons
endGame = false;
} else {
endGame = true;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
Your random number generation is done outside of your while loop so when they input that they want to continue the game it should then generate a new number:
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input.equals("Yes")) {
randNum = r.nextInt(100-1+1) + 1;
correctGuess = false;
} else {
break;
}
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");
}
}
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to write a program that randomly generates a number and the user tries to guess the number. The program keeps count of how many tries it took to guess the right number. The issue that I am having is getting past the while loop. When I run the program, it doesn't go past the while loop until I hit -1, in which case it outputs "Your number is too low". I am not real sure where I went wrong.
import java.util.Scanner;
import java.util.Random;
public class DoGuessingGame
{
public static void main(String[] args)
{
int number1, userInput; //assign vars
int tries = 0;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in); //define Random and scanner input
System.out.println("Welcome to the Guessing Game!");
System.out.println("-----------------------------");
number1 = rand.nextInt(20) + 1;
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
}
while(userInput != -1);
{
if (userInput > 0 && userInput < 21)
{
if(userInput == number1)
{
System.out.println("That is the correct number");
tries++;
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
}
else if(userInput > number1)
{
System.out.println("Your number is too high");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
else if(userInput < number1);
{
System.out.println("Your number is too low");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
}
else
{
System.out.println("Please enter a number between 1 and 20");
}
}
System.out.println("The number of tries: " + tries);
}
}
Your nesting and placement of braces is confusing. No wonder you're having problems.
Learn to pay more attention to style and readability.
I did not compile or run your code. I didn't think too deeply to see if you did this correctly. But I might do it more like this:
import java.util.Scanner;
import java.util.Random;
public class DoGuessingGame
{
public static void main(String[] args) {
int number1, userInput; //assign vars
int tries = 0;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in); //define Random and scanner input
System.out.println("Welcome to the Guessing Game!");
System.out.println("-----------------------------");
number1 = rand.nextInt(20) + 1;
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
if (userInput > 0 && userInput < 21) {
if(userInput == number1) {
System.out.println("That is the correct number");
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
userInput = -1;
} else if(userInput > number1) {
System.out.println("Your number is too high");
System.out.println("Please try again");
} else if(userInput < number1) {
System.out.println("Your number is too low");
System.out.println("Please try again");
}
} else {
System.out.println("Please enter a number between 1 and 20");
}
} while(userInput != -1);
System.out.println("The number of tries: " + tries);
}
You have an extra pair of braces directly after your do-while loop, as well as a semicolon directly after an if-statement which will alter the flow of your program.
else if(userInput < number1);
Your do/while loop is not doing what you think. You have:
do {
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
} while(userInput != -1);
Code below this point is executing after the do while loop, hence userInput will always be -1 when you reach here!
I think your do.... while loop should look like this
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
if (userInput > 0 && userInput < 21)
{
if(userInput == number1)
{
System.out.println("That is the correct number");
tries++;
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
}
else if(userInput > number1)
{
System.out.println("Your number is too high");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
else if(userInput < number1);
{
System.out.println("Your number is too low");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
}
else
{
System.out.println("Please enter a number between 1 and 20");
}
}
while(userInput != -1);
I am writing a program that will ask the user to guess a random number 6 times. The program has to ask if they want to play again and will keep a running total of the wins/losses.
How would I have the program rerun?
heres the code:
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
String input;
double guess = 0;
int number;
double wins = 0;
double losses = 0;
String repeat;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to Higher/Lower!");
System.out.println("Enter your name: ");
input = keyboard.nextLine();
while(input.equalsIgnoreCase("yes")); {
number = randomNumbers.nextInt(100) + 1;
System.out.println("I've chosen my number, " + input + "You only have 6 tries, good luck!"); }
for(int num = 1; number != guess && number <= 6; num++) {
System.out.println("Enter guess " + num + ":");
guess = keyboard.nextDouble();
if(guess < number)
System.out.println("higher.");
else if(guess > number)
System.out.println("lower.");
else
System.out.println("Congratulations!"); }
if(guess == number) {
System.out.println("You guesses my number!"); wins++; }
if(guess != number) {
System.out.println("Sorry, " + input + " my number was " + number +
"You lose!"); losses++; }
System.out.println("Do you want to play again? (Yes/No): ");
repeat = keyboard.nextLine();
if(input.equalsIgnoreCase("no")); {
System.out.println("Thanks for playing!"); }
System.out.println(wins + " wins");
System.out.println(losses + " losses");
}
}
It is skipping over asking me if i want to play again or not and i dont know what kind of loop to use
Wihtout your code, I'm assuming this is what you need.
boolean doContinue = true;
do {
//guess random number 6 times
//do you want to continue?
// yes -> doContinue = true;
// no -> doContinue = false;
} while (doContinue );
I would suggest making your loop a do-while loop like this:
do {
for (int i=0; i<6; i++){
/*
insert code for the guessing/checking/etc.
*/
}
System.out.print("Would you like to continue? [Y/n] ");
} while (scan.next().toUpperCase().charAt(0) != 'Y');