In this program, the computer generates a random number (between 1-100) and the user attempts to guess it.
Runs until the user correctly guesses the number. Needs to print out the total number of tries it took before the number was guessed correctly.
Program runs fine, but there is a logical error. Nothing prints out when I correctly guess the number; the program just stops instead.
import java.util.*;
public class Problem3 {
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
int num = rand.nextInt(100)+1;
System.out.println(num); //prints out the random number so I know test works correctly
int count = 0;
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
console = new Scanner(System.in);
int guess = console.nextInt();
while(guess != num){ //while guess is not = to number
if(guess < num){ //if less than num
System.out.println("Your guess is too low");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else if( guess > num){ //if greater than num
System.out.println("Your guess is too high");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else{
count++;
System.out.println("You guessed correctly after " + count + " tries!");
}
}
}
}
Actually you never enter the else stage, because when the number is guessed, the while code won't execute and therefore the else code will never execute. So after that the number is guessed, so condition is false, exit while loop and System.out.print the Congrats message
Put this outside your while loop "at the end":
System.out.println("You guessed correctly after " + count + " tries!");
Here's what your code should look like:
while(guess != num){ //while guess is not = to number
if(guess < num){ //if less than num
System.out.println("Your guess is too low");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else{ //if greater than num
System.out.println("Your guess is too high");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}
}
System.out.println("You guessed correctly after " + ++count + " tries!");
Your while loop condition becomes false when the correct number is guessed. This makes the else unreachable.
EDIT
Here is how I would have tackled your problem. If you find yourself repeating code, it usually means there is an opportunity for improvement. Not only is there less code, but it is easier to read and follow what is going on. I'm not trying to steal the answer (#AmirBawab found the issue first), but I am a big believer in not just making code that works, but code that can be maintained and read by others. Hopefully as you continue learning you will keep that in mind. Happy coding!
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
int num = rand.nextInt(100) + 1;
int count = 0;
while (true) {
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
int guess = console.nextInt();
count++;
if (guess < num) {
System.out.println("Your guess is too low");
} else if (guess > num) {
System.out.println("Your guess is too high");
} else {
System.out.println("You guessed correctly after " + count + " tries!");
break;
}
}
console.close();
}
Related
This is a Hi-Lo number guessing game code, and the program ends either when the user gets the correct number or enters -1 while playing the game.
Here, I was wondering if it is possible to make the program run again even after the user enters -1 and the game ends, for example, in a situation where the user feels like restarting the game without finishing the first game.
import java.util.Random;
import java.util.Scanner;
public class HighLowGame {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
int guess = scanner.nextInt();
**//if user enters -1, the game ends
if(guess == -1){
break;
}**
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
count = 0;
System.out.println("Would you like to play the game again?(yes/no): ");
String another = scanner.next();
if (another.equalsIgnoreCase("no")) {
break;
}
// if the user wants to play the game one more time, it starts again
else {
number = generator.nextInt(100) + 1;
System.out.println("Please guess the number(Enter -1 to quit): ");
}
}
}
}
}
You can just put the game into a method, and when the method ends, you just ask them.
Main:
public static void main(String[] args){
boolean flag = true;
while(flag){
play();//play the game
Scanner input = new Scanner(System.in);//read the respound
System.out.println("want to play again?");
if(input.nextLine().equal("no"){//Want to play? BTW: I'm assuming you only enter "no" or "yes"
flag = false;//Don't want to play
}
}
}
And the method:
public static void play(){
//create scanner, variables and a random number
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
//prompt user to enter a number
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
//user enters a number
int guess = scanner.nextInt();
//if user enters -1, the game ends
if(guess == -1){
break;
}
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
//displays the message and the attempt count
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
}
}
}
BTW: you said when the user enters -1, you end the game, then why in the world do you want to ask the user again ?_?
I'm trying to have my loop only occur three times. So if the user doesn't guess the correct number after their third guess then the loop ends which I have but it doesn't display what the number was. I need the number displayed after the third guess but not sure why it's not displaying the correct number.
import java.util.Scanner;
public class GuessNumberDoWhileA {
public static void main(String[] args) {
//Generate random number from 1-10
int number = (int) (Math.random()*9 + 1);
int count = 0;
//Auto Generated Method stub
Scanner Input = new Scanner(System.in);
//Tell the user to guess a number
System.out.println("Guess a number between 1 and 10");
//int guess = -1;
//while (guess != number) {
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number)
System.out.println("Correct the number was " + number);
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
else
System.out.println("The correct number is " + number);
}
System.out.println("The number was " + number);
}
}
You need a boolean variable that can be used to check whether user was able to guess the number correctly or not. Initial value of this boolean variable should be false.
You don't need the last else statement in the loop. If user guesses the number correctly, set the boolean variable to true and break out of the loop. After the loop, check if the boolean variable is false or not. If it is false, that means user was not able to guess the number, so display the correct number to the user.
If user is able to guess the number then the first if statement in the loop will print the correct number on the console and break out of the loop. It will also set the boolean variable to true, so correct number will be printed only once on the console.
boolean guessed = false;
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number) {
System.out.println("Correct the number was " + number);
guessed = true;
break;
}
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
}
if (!guessed) System.out.println("Number was: " + number);
Ok I need help on a school assignment that I'm currently stuck on and I need a lot of help. I have tried to do this for hours and still cant figure out on how to do this assignment. This is my code below.
I'm trying to create a guessing game. What I'm stuck on is how I'm suppose to loop the number of 10 guesses and no more. I tried it and it gives me an infinite loop.
What im trying to create:
A number from 1 and 100 is picked and the player does not know what the number is.
The player is asked to guess a number from 1 to 100.
They have 10 chances to guess the right number.
If the player does not guess the correct number within 10 guesses then the player loses the game.
You let them know if their guess is too low or too high to help them narrow down their guesses to eventually guess the right number before their 10 guesses are used up.
import java.util.Scanner;
import java.util.Random;
public class GuessGame3
{
public static void main (String[] args){
int num1;
int count=0;
int Guess=0;
Random generator = new Random();
Scanner scan = new Scanner(System.in);
//get generator
num1 = generator.nextInt(100) + 1;
while (Guess != num1){
System.out.println("Enter a number between 1 and 100");
Guess = scan.nextInt();
count++;
while (count > 10)
System.out.println("Sorry you didnt guess in 10 trues its been " + count + " tries");
if ( Guess > num1)
{
System.out.println("Lower!");
}
else if (Guess < num1)
{
System.out.println("Higher");
}
else
System.out.println("Congratz with " + count + " amount of tries");
}
}
}
I recommend putting the checks if the guess is as part of the first while loop, not a nested one.:
while (count < 10){
System.out.println("Enter a number between 1 and 100");
Guess = scan.nextInt();
count++;
if ( Guess > num1)
{
System.out.println("Lower!");
}
else if (Guess < num1)
{
System.out.println("Higher");
}
else {
break;
}
}
if(count < 10) {
System.out.println("Congrats! You have completed it in " + count + " tries!");
} else {
System.out.println("Sorry you have run out of your 10 guesses!");
}
There might be some errors here, but you should get the gist.
Problem lies with the loop and in the order you have validated the total number of tries and the Guess match. Try the below
import java.util.Scanner;
import java.util.Random;
public class TestGame
{
public static void main(String[] args)
{
int num1;
int count = 0;
int Guess = 0;
int maxAllowedRetries = 10;
Random generator = new Random();
Scanner scan = new Scanner(System.in);
//get generator
num1 = generator.nextInt(100) + 1;
while(count <= maxAllowedRetries)
{
if(count == maxAllowedRetries)
{
System.out.println("Sorry you have reached maximum number of retries!");
break;
}
count++;
System.out.println("Enter a number between 1 and 100");
Guess = scan.nextInt();
if(Guess == num1)
{
System.out.println("Great you got it Right!");
break;
}
System.out.println("Sorry you didnt guess right. Its been " + count + " tries");
if(Guess > num1)
{
System.out.println("Lower!");
}
else if(Guess < num1)
{
System.out.println("Higher");
}
}
}
}
This Java program is supposed to ask the user to input a maximum value, and then generate a random number between 1 and that maximum value. The user then guesses what the value is until they get it right. When the user is incorrect, the program tells them that they're too high or too low and increments the number of guesses. If the user is correct, the program displays the total number of guesses and asks the user if they would like to play again.
The issue I keep having is that sometimes, when I input a guess, the program skips over telling me I was too high, too low, or correct, and simply asks me if I would like to play again. I can't figure out why this is happening, and it seems to happen randomly.
import java.util.Scanner;
public class GuessNumber
{
public static void main (String [] args)
{
Scanner in = new Scanner (System.in); //create scanner object
int maxNumber = 0; //declare variables
int userGuess = 0;
int totalGuesses = 0;
int secretNumber = 0;
String replay = "";
System.out.println("Welcome to the Secret Number Generator!");
do
{
System.out.println("Please input a maximum value for the secret number and press enter."); //prompt user to input a maximum value
maxNumber = in.nextInt();
secretNumber = (int) ((Math.random() * maxNumber) + 1); //generate the secret number
System.out.println("A new secret number has been chosen!"
+ "\nWhat do you think it is? Input your guess and press enter."); //prompt user to input a guess
userGuess = in.nextInt();
while (userGuess < secretNumber) //while user's guess is less than the secret number
{
System.out.println("Sorry, that is too low! Please try again."); //prompt user to input another guess; increment total number of guesses by 1
userGuess = in.nextInt();
totalGuesses ++;
}
while (userGuess > secretNumber) //while user's guess is greater than the secret number
{
System.out.println("Sorry, that is too high! Please try again."); //prompt user to input another guess; increment total number of guesses by 1
userGuess = in.nextInt();
totalGuesses ++;
}
if (userGuess == secretNumber) //if user guesses correctly
{
System.out.println("Nice job! Your guess, " + secretNumber + " is correct!" //congratulate and display total number of guesses
+ "\nTotal number of guesses: " + totalGuesses);
}
System.out.println("Would you like to play again? Please input \"Yes\" or \"No\" and press enter."); //ask user if they would like to play again
replay = in.next();
while (!replay.equalsIgnoreCase("Yes") && !replay.equalsIgnoreCase("No") //in case of invalid input
&& !replay.equalsIgnoreCase("\"Yes\"") && !replay.equalsIgnoreCase("\"No\""))
{
System.out.println("Sorry, that is an invalid input. Please input \"Yes\" or \"No\" and press enter.");
replay = in.next();
}
}
while(replay.equalsIgnoreCase("Yes") || replay.equalsIgnoreCase("\"Yes\"")); //replay while user says yes
if (replay.equalsIgnoreCase("No") || replay.equalsIgnoreCase("\"No\"")) //if user says no
{
System.out.print("Thanks for playing!");
}
} //end of main method
} //end of class GuessNumber
you have multiple while loops which doesn't make sense. if user enters bigger number then enter small one it will skip it.
you can shrink them all to one of them
while (userGuess != secretNumber){
if(userGuess > secretNumber){
//too high
} else if(userGuess < secretNumber){
//too low
} else{
//nice got it
}
}
//do you want to play again
...
Don't use while loops for single evaluation conditions. Replace your three inner while loops with something like this (pseudocode):
int guess = readInteger()
while guess != number
if guess < number print "too low"
if guess > number print "too high"
assert guess == number
print "you guessed correctly; good job!"
And then run that through the game loop that keeps the game going.
Looks like you are having some looping troubles, and like the others suggest please avoid so many unnecessary nested loops when a simple selection structure like "if else" or "select case" will work. Should save you some fuss that way too.
To make your app run more predictably I would suggest throwing the "game" logic into a method. Here is an example that runs. Hope it helps you out some!
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String replay = "";
do {
runGame(); //run method to guess number
System.out.println("Play again? Enter Yes or No");
replay = in.nextLine().toLowerCase();
}
while(!replay.equals("no"));
}
private static void runGame() {
Scanner in = new Scanner(System.in); //create scanner object
int maxNumber = 0; //declare variables
int userGuess = 0;
int totalGuesses = 0;
int secretNumber = 0;
System.out.println("Welcome to the Secret Number Generator!");
System.out.println("Please input a maximum value for the secret number and press enter."); //prompt user to input a maximum value
maxNumber = in.nextInt();
secretNumber = (int) ((Math.random() * maxNumber) + 1); //generate the secret number
System.out.println("A new secret number has been chosen!" + "\nWhat do you think it is? Input your guess and press enter."); //prompt user to input a guess
userGuess = in.nextInt();
while (userGuess != secretNumber) {
if (userGuess < secretNumber) {
System.out.println("Sorry, that is too low! Please try again."); //prompt user to input another guess; increment total number of guesses by 1
} else if (userGuess > secretNumber) {
System.out.println("Sorry, that is too High! Please try again."); //prompt user to input another guess; increment total number of guesses by 1
}
else {
System.out.println("Sorry, but that's not right. Try again...");
}
totalGuesses++;
userGuess = in.nextInt();
}
System.out.println("You guessed it! After " + totalGuesses + " tries.");
}
}
the application is a simple guessing game which i got that part down. my issue is making a method that before any guessing starts the player must first guess the right amount of digits in a number
e.g the guess being 314 and the answers has 3 digits in it then the guessing of too high two low starts otherwise it keeps looping until you guess the right amount of digits.
now i have created the method to do this my issue is a rather simple one i think but its a matter of initializing the variables and that's where i am having problems.
import java.util.Random;
import java.util.Scanner;
public class NumberGuess
{
public static void main (String[] args)
{
final int MAX = 1000;
int answer, guess;
Scanner Keyboard = new Scanner(System.in);
Random generator = new Random(); //Random generator. 1 to 100.
answer = generator.nextInt(MAX) +1;
guess = Keyboard.nextInt();
System.out.print ("I'm thinking of a number between 1 and "+ MAX + ". Guess what it is: (or enter 0 to quit) ");
do
{
System.out.print("Guess what the number is: ");
guess = Keyboard.nextInt();
if (guess > answer && guess != 0)
System.out.println("Your guess is too high!");
else if (guess < answer && guess !=0)
System.out.println("Your guess is too low!");
if(guess==0)
System.out.println("you have ended your game");
else if (guess == answer)
System.out.println("You got it!");
} while (guess != answer&& guess!=0);
}
int NumOfDigits(int number)
{
int numDigits = 0;
while (number/10 > 0);
{
number = number/10;
numDigits++;
}
return numDigits;
}
int guess;
Scanner Keyboard1 = new Scanner(System.in);
guess = Keyboard1.nextInt();
int target = NumOfDigits(answer);
while(NumOfDigits(guess) != target);
{
System.out.println("read anothrer input guess");
guess = Keyboard1.nextInt();
}
System.out.println("you got the correct number of digits now guess the number!");
guess = Keyboard1.nextInt();
}
your method for counting diigits is wrong it should be like this
public static int NumOfDigits(int number)
{
int numofdigits = 0;
while(number>0){
numofdigits++;
number = number/10;
}
return numofdigits;
}
because your method returns 2 and it should return 3