trying to create a Random number generator within a while loop that controls the Number Guessing Game. The issue is the "too high" and "too low" hints will say one number (ex:35) is too low, but then say the nest input number (ex:36) is too high. Then when I move the call a random function in the nested while loop, it generates the same random number each time.
I have tried moving the call to random function to my most inner loop, but then it generates the same random number. Currently, it is in the outer while loop, but then the issue of the high/lows occurs
import java.util.Scanner;
import java.util.Random;
public class numberGuessingGame
{
public static void main (String[] args)
{
int randomNumber, userNumber = 0, guesses = 0, correct;
final int MAX = 100;
char playAgain, playGame = 'y';
//ask user if they wish to play
System.out.println("Would you like to play the Number Guessing Game? y / n");
Scanner scan = new Scanner (System.in);
playGame = scan.next().charAt(0);
Random generator = new Random();
//while loop to continue to exacute game as long as user enters 'y'
while (playGame == 'y'){
if (playGame != 'y')
break;
randomNumber = generator.nextInt(MAX) + 1;
//flag
correct = 0;
//loop to control the round
while (correct == 0) {
//get user number
System.out.println("Please pick a number between 1 and 100.");
userNumber = scan.nextInt();
//high and low sugguestion
if (userNumber > randomNumber)
System.out.println("Number is too high, try something lower.");
if (userNumber < randomNumber)
System.out.println("Number is too low, try something higher.");
if (userNumber == randomNumber){
System.out.println("That number is correct!");
System.out.println("Would you like to play again? y/n");
playGame = scan.next().charAt(0);
}
guesses++;
System.out.println("You have guessed " + guesses + " times!");
}
}
//break statement skips here when 'n' is entered in
// the game prompting question
System.out.println("Thanks for playing, have a nice day!");
}
}
I'd like to suggest some changes you might consider:
use a boolean for correct rather than an int
remove your if statement immediately after the while: it is redundant
use do-while when the loop must be executed at least once
use Integer.compareTo rather than separate comparisons
Your inner loop does not terminate that's why you have the same
randomNumber, change correct=0 value to terminate the inner while loop
if (userNumber == randomNumber){
System.out.println("That number is correct!");
System.out.println("Would you like to play again? y/n");
playGame = scan.next().charAt(0);
correct=1; //Just to remove correct=0 value
}
Related
I've just started learning programming for the first time and I am working through Java to start. I am doing a common coding exercise of programming a guessing game using loops and conditionals. My program is required to do the following:
Pick a random number between 1 and 100
Repeatedly prompt the user to guess the number
Report to the user that he or she is correct or that the guess is high
or low after each guess
Offer the user the option to quit mid-game
Count the number of guesses in a game and report the number upon a correct guess
Ask the user if they want to play again upon a successful game
I have been a little bit shaky with loop syntax so far and need some help with my program because there are a lot of issues I don't know how to fix. Would anyone be kind enough to lend me a hand? Please forgive the many probably obvious mistakes.
import java.util.Scanner;
import java.util.Random;
public class Guess
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess = 0, count = 0;
String another = "y";
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
Scanner scan = new Scanner(System.in);
System.out.println("I'm thinking of a number between 1 and " + MAX
+ ". Guess what it is: ");
guess = scan.nextInt();
while (another.equalsIgnoreCase("y"))
{
while (guess != answer)
{
while (guess > MAX || guess < 1)
{
System.out.println("Invalid input. Please re-enter a number"
+ " between 1 and " + MAX + ":");
guess = scan.nextInt();
}
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
}
else if (guess > answer)
{
count++;
System.out.println("You guessed too high. Guess again? Y/N:");
another = scan.nextLine();
}
else if (guess < answer)
{
count++;
System.out.println("You guessed too low. Guess again? Y/N:");
another = scan.nextLine();
}
}
}
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
}
One problem is that you're not letting the user quit midway through the game because even if the user guesses a number within the 1 to 100 range and doesn't get the right answer, his or her answer to Guess again: Y/N: won't be checked since the current loop it is in only compares guess to answer, never another. Therefore, you'll end up being in an infinite loop in this case because if the user guesses 57 when the answer is 50, you'll just continuously prompt the user if he or she wants to guess again.
My recommendation would be to remove the second while loop
while (guess != answer)
{
//other stuff
}
and place the code inside that loop into the outside while loop
while(another.equalsIgnoreCase("y")){
//other stuff
}
And if you want the user to be able to play again, I would recommend putting this snippet of code you had earlier inside the if statement where you check if the user has guessed correctly,
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
This way, if the user wins the game, their choice to play again will be checked in the while loop. One last thing I would recommend is moving this line
guess = scan.nextInt();
inside the while loop that checks another so that if the user wants to play again, the game will prompt the user for a guess.
I am fairly new to programming Java. I want to make a lotto program. Here is the code:
package me.nutella;
import java.util.Scanner;
public class Lotto {
#SuppressWarnings("resource")
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter A Number Between 1-20!");
int choice = scanner.nextInt();
if (choice > 20)
System.out.print("Please Only Pick Numbers Between 1-20!");
int b = (int) (Math.random() * 20) +1;
if (choice == b)
System.out.print("You Win!");
else
System.out.print("You Lost! The correct answer was " + b);
}
catch(Exception E) {
System.out.print("Your Answer Must Be Numeric!");
}
}
}
Now, this part if what I am mainly concerned about:
if (choice > 20)
System.out.print("Please Only Pick Numbers Between 1-20!");
I want to make it so if someone puts the number over 20, it will print that message. Now this part does work, but when I put the number over 20, it still plays the lotto game. I want to make it so if they put their number higher than 20, it will not play the game and enter that message.
How can this be done?
Can be most elegantly done using a do {...} while(); loop. At the beginning, the user must always enter a number, so the loop MUST execute at least once. This is where a do {...} while(); loop comes in handy. You can display your message at the beginning of the loop, then read in the users input. If it is in an acceptable range, the loop never re-executes, and the code moves on. But, if it is not acceptable, we re-execute the loop until we get an acceptable value.
Below is how I would approach this problem:
Scanner scanner = new Scanner(System.in);
int choice = 0;
do {
System.out.print("Please Pick A Number Between 1-20!");
choice = scanner.nextInt();
} while(choice > 20 || choice < 1);
It is also worth noting that your message states that "Number between 1-20", but your code only checks that choice < 20, so if a user enter anything LESS THAN 20, it would be accepted. This includes 0, negatives, and of course the valid number range. I added the || choice < 1 check in my example.
What you need is a loop to keep getting inputs if input is not valid:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter A Number Between 1-20!");
int choice = scanner.nextInt();
boolean validInput=false;
while(!validInput) {
int choice = scanner.nextInt();
if (choice > 20) {
System.out.print("Please Only Pick Numbers Between 1-20!");
} else {
validInput=true;
}
}
int b = (int) (Math.random() * 20) +1;
if (choice == b)
System.out.print("You Win!");
else
System.out.print("You Lost! The correct answer was " + b);
Write a program that generates a random number (between 1 and 10) and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” The program should use a loop that repeats until the user correctly guesses the random number.
This is my code and when I run it, it will not stop looping and I have no idea why. Thank you!!
/////guess/////
import java.util.Random;
import java.util.Scanner;
public class guess
{
public static void main (String [] args)
{
Random rand = new Random();
int numberToGuess =rand.nextInt(10);
Scanner input=new Scanner(System.in);
int guess;
boolean win =false;
while (win == false)
System.out.println("Guess a number between 1 and 10");
guess = input.nextInt();
{
if(guess == numberToGuess)
win=true;
}
if(guess<numberToGuess)
{
System.out.println("Your guess is too low");
}
{
if (guess > numberToGuess)
System.out.println("Your guess is too high");
System.out.println("You win!");
System.out.println("The number was" +numberToGuess);
}
}
}
This doesn't just apply to while statements; if and for statements are affected by this as well.
Your while statement will only ever execute the next line if it is not contained in a block.
// Without curly braces, the println is the only thing in the loop.
while (win == false)
System.out.println("Guess a number between 1 and 10");
// This isn't part of the loop!
guess = input.nextInt();
You fix this by ensuring that everything you want to loop on is contained by curly braces:
while(!win) {
// ALL of the logic you want to execute while win is false
}
Provided you have copied your code as is, have a look at your while loop you have no {} so it will keep printing
System.out.println("Guess a number between 1 and 10");
until win changes, which in this code it won't.
We are meant to to create a program in java in which the computer randomly guesses a number between 1-100 and allows the user to guess to the number. If the number is lower than the random number the program should say: lower! and of higher, the program should say: higher! If the user guesses the right number it should say congratulations you guessed the right number in X amount of tries, This is what I have so far, when I execute in cmd it just spams either higher or lower and I need help working it out.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame{
public static void main(String[] args) {
int random, guess, attempts;
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
random = generator.nextInt(100) + 1;
attempts = 1;
System.out.print("I am thinking of a number between 0 and 100, what do you think it is?");
guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
}
System.out.print(random + "is the correct answer and it took you" + attempts + "attempts to guess it!");
}
}
You're only reading the input once and then looping on it forever (you read the input outside the loop).
Try reading the input inside the loop and using do-while loop:
guess = 0;
do {
guess = keyboard.nextInt();
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
} else {
System.out.print("Higher!");
attempts +=1;
}
} while (guess != random);
Place the guess = keyboard.nextInt(); into the while loop to ask again and again.
You only take a single guess and stuck yourself in the while loop, it's like if the number randomized by the program is 70, and for example if the user gave his first attempt as 50, the code will enter the while loop as the number is not 70, but it won't come out as you coded while(guess != random) and guess will ever equal random in our case, and it will be always lower for an infinite time because you give him the ability to enter a single attempt and then you enter an endless while loop without giving him the ability to change his attempt through it, So, you must allow him to has his second, third, ..etc attempts inside the while loop itself, like the following:
guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
guess = keyboard.nextInt();
}
The random number generate the number once the we will call the method isNumCorrect again using while loop until it returns true and the guess count will increase every time the number pass through isNumCorrect
import java.util.Random;
import java.util.Scanner;
class guessGame {
int guessedNumber;
int userNumber;
int guess_count;
public guessGame() {
Random rand = new Random();
guessedNumber = rand.nextInt(100);
}
void userNum() {
System.out.println("GUESS THE NUMBER");
Scanner sc = new Scanner(System.in);
userNumber = sc.nextInt();
}
boolean isNumCorrect() {
guess_count++;
if (userNumber == guessedNumber) {
System.out.printf("yes you guessed it right in %d guesses", guess_count);
return true;
} else if (userNumber < guessedNumber) {
System.out.println("too low");
} else {
System.out.println("too high");
}
return false;
}
}
public class cwh_42_guess_the_number {
public static void main(String[] args) {
guessGame g = new guessGame();
boolean b = false;
while (!b) {
g.userNum();
b = g.isNumCorrect();
}
}
}
I'm practicing Java and i tried to make a guess game but i want the game to ask for input again when the user don't guess the number right. When i guess the number wrong the loop just continuous to guess numbers until the number is the right one and the game ends.
import java.util.*;
class GuessGame {
private Scanner userInput = new Scanner(System.in);
public GuessGame(){
System.out.println("~~~Guess Game~~~");
System.out.println("~~~Guess a number between 0 and 9~~~");
}
int guessedNumber = 0;
public void gameStart(){
System.out.println("Guess a number: ");
boolean guessedRight = false;
boolean gameOn = true;
int userNumber = userInput.nextInt();
while(gameOn){
guessedNumber = userNumber;
int randomNumber = (int) (Math.random() * 10);
if(randomNumber == guessedNumber){
guessedRight = true;
}
if(guessedRight){
System.out.println("You guessed " + guessedNumber);
System.out.println("The number is " + randomNumber);
System.out.println("You won!!!");
System.out.println("Game Over!!!");
break;
}else{
System.out.println("You guessed " + guessedNumber);
System.out.println("The number is " + randomNumber);
System.out.println("Try again!!!");
}
}
}
}
The int userNumber = userInput.nextInt(); line is responsible for getting the number that the user entered from the input line. Moving this line inside the while loop will ask for a number each time the loop is ran (which is only once if the user guesses right the first time).
Just call the method from a loop:
public GuessGame(){
while(true) {
System.out.println("~~~Guess Game~~~");
System.out.println("~~~Guess a number between 0 and 9~~~");
gameStart();
}
}
This will simply restart the game as soon as the gameStart() method exists. (Which is when the user has guessed the right number)