For my Java class, I'm supposed to make a random number guessing game. I've been stuck on a loop I created for the past couple of days. The output of the program is always an infinite loop and I can't see why. Any help is very much appreciated.
/*
This program will generate a random number.
It will ask the user to guess what number was generated and say
if the guess is too high or low.
*/
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
while(success == 0)
{
if(userGuess > randNum){
System.out.println("Too high");
}
else if(userGuess < randNum){
System.out.println("Too high");
}
else{
System.out.println("Something is very wrong.");
}
}
if(userGuess == randNum){
success++;
System.out.println("You got it! Play again?");
}
}
}
You put the if that checks if the input is equal to the number outside the while, so the cycle never ends.
Here is the code fixed:
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
while(success == 0) {
if(userGuess > randNum) {
System.out.println("Too high");
} else if(userGuess < randNum) {
System.out.println("Too high");
} else if(userGuess == randNum) {
success++;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}
I fixed it! I added breaks after each fail condition so that I wouldn't get an infinite loop. I tried this earlier, but I kept getting errors.
This is the completed code:
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
boolean success = false;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
input.close();
while(success == false){
if(userGuess > randNum) {
System.out.println("Too high,try again");
break;
} else if(userGuess < randNum) {
System.out.println("Too low");
break;
} else if(userGuess == randNum) {
success = true;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}
Related
I'm a beginner at coding in Java and for my practice is a number guessing game.
I have at least 90% of the code right but my only problem is I do not know how I can make it keep the player input answers when instead of an integer, they input a letter or word.
Here's my code:
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Random number = new Random();
int numberToGuess = number.nextInt(50);
int numberOfTries = 0;
int guess;
boolean win = false;
try {
while (win == false) {
System.out.println("Guess a number between 1 to 50:");
guess = s.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess < 0) {
System.out.println("Invalid Number");
} else if (guess >= 51) {
System.out.println("Number Exceeds Limit");
} else if (guess < numberToGuess) {
System.out.println("Too low; Guess again~");
} else if (guess > numberToGuess) {
System.out.println("Too high; Guess again~");
} else {
System.out.println("I think that is incorrect...");
}
}
System.out.println("You Win!");
System.out.println("The Number was:" + numberToGuess);
System.out.println("It took you:" + numberOfTries + " tries");
} catch (InputMismatchException e) {
System.out.println("I think something is wrong...");
} finally {
System.out.println("Please restart the Game if you wish to continue. Sorry for the Inconveniece");
}
}
}
This will work until the user inputs an integer;
boolean flag =true;
while(flag){
try {
Integer.parseInt(new Scanner(System.in).next());
flag=false;
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n");
}
}
Hi I'm currently having trouble throwing exceptions on my guessing game code. I want to put an exception for string input (instead of int) and also an exception for entering a number beyond the limit(50). Thanks.
public static void main (String[] args)
{
Random ran = new Random();
int numberToGuess = ran.nextInt(50)+1;
int numberOfTries = 0;
Scanner input = new Scanner (System.in);
int guess;
boolean win = false;
while (win == false)
{
System.out.println("Guess a number from 1 to 50!");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess)
{
win = true;
}
else if (guess < numberToGuess)
{
System.out.println("Too low. Try again.");
}
else if (guess > numberToGuess)
{
System.out.println("Too high. Try again.");
}
}
System.out.println("You got it in " + numberOfTries + " attempt(s)!");
}
Here is a potential solution:
import org.apache.commons.lang3.StringUtils;
import java.util.Random;
import java.util.Scanner;
public class StackOverflow45419907 {
private final Scanner input;
final int numberToGuess;
public StackOverflow45419907() {
this.input = new Scanner(System.in);
numberToGuess = new Random().nextInt(50) + 1;
}
public static void main(String[] args) {
new StackOverflow45419907().playGame();
}
private void playGame() {
int numberOfTries = 0;
int guess = -1;
while (guess != numberToGuess) {
guess = collectGuess();
numberOfTries++;
printClue(guess);
}
System.out.println("You got it in " + numberOfTries + " attempt(s)!");
}
private void printClue(int guess) {
if (guess < numberToGuess) {
System.out.println("Too low. Try again.");
} else if (guess > numberToGuess) {
System.out.println("Too high. Try again.");
}
}
private int collectGuess() {
System.out.println("Guess a number from 1 to 50!");
final String potentialGuess = input.nextLine();
return validateAndParse(potentialGuess);
}
private int validateAndParse(String potentialGuess) {
if (!StringUtils.isNumeric(potentialGuess)) {
throw new IllegalArgumentException("not numeric: " + potentialGuess);
}
final int asInt = Integer.parseInt(potentialGuess);
if (asInt > 50 || asInt < 1) {
throw new IllegalArgumentException("value out of valid range: " + asInt);
}
return asInt;
}
}
I don't really think you need to throw exception. you can use
Scanner#hasNextInt() to validate the input is integer. then assign it to the guess variable and just check if its bigger then 50.
If you really what to throw exception. use
throw new RuntimeException(message) if the input is not an integer or it is larger than 50.
Edit:
I wont use it like that, but I believe you just want to know about the exceptions.
System.out.println("Guess a number from 1 to 50!");
numberOfTries++;
if (!input.hasNextInt())
throw new IllegalArgumentException("Input must be a number");
guess = input.nextInt();
if (guess < 1 || guess > 50)
throw new IllegalArgumentException("Input must be a number from 1 to 50");
How would I limit the tries of a simple game to just three? I would think you would use a boolean. But not sure.
import java.util.Scanner;
public class guess {
public static void main(String[] args) {
int randomN = (int) (Math.random() * 10) + 1;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
do {
System.out.print("Enter your guess: ");
guess = input.nextInt();
if (guess == randomN) {
System.out.println("You won!");
} else if (guess > randomN) {
System.out.println("Too high");
} else if (guess < randomN) {
System.out.println("Too low");
}
} while (guess != randomN);
}
}
int attempts = 0;
do{
attempts++;
....
}while(guess != randomN && attempts < 3);
Use a flag. Initialize it as 0. If guess is correct then reset it as 0. If not increase by 1. Before each guess, check if flag > 2. If no let continue, if yes break.
You can increment during the failure of a guess. I believe the variable should be located outside of the loop. Then what's left is to add a portion that notifies the user of a failure when guesses run out.
public static void main(String[]args) {
int rNumber = (int)(Math.random() * 10) + 1;
Scanner input = new Scanner(System.in);
int guess;
int tries = 0;
int success = 0;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
do {
System.out.println("Enter your guess: ");
guess = input.nextInt();
if(guess == rNumber) {
System.out.println("You guessed right! You win!");
success++;
} else if (guess < rNumber) {
System.out.println("Too low");
tries++;
} else if (guess > rNumber) {
System.out.println("Too high.");
tries++;
}
} while(tries != 3 && success != 1 || success != 1);
}
I tried to create basic number find game (1-100).
But always the program terminated after second try.
Code:
Random rnd = new Random();
int rndm = rnd.nextInt(100);
int tryn;
Scanner sc = new Scanner(System.in);
System.out.print("Guess: ");
tryn = sc.nextInt();
if (tryn == rndm) {
System.out.println("You win.");
sc.close();
}
else if (tryn > rndm) {
System.out.println("Too high.");
System.out.print("Guess again: ");
tryn = sc.nextInt();
}
else {
System.out.println("Too low.");
System.out.print("Guess again: ");
tryn = sc.nextInt();
}
When I run output like:
<terminated> test2 [Java Application]...
Guess: 30
Too low.
Guess again: 50
Why my program doesn't loop? Thanks for any help.
Add a loop in your code...
while(tryn != rndm){
Please see the following code (I have tested it):
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Random rnd = new Random();
int rndm = rnd.nextInt(100);
int tryn;
Scanner sc = new Scanner(System.in);
System.out.print("Guess: ");
while (sc.hasNextInt()) {
tryn = sc.nextInt();
if (tryn == rndm) {
System.out.println("You win.");
break;
} else if (tryn > rndm) {
System.out.println("Too high.");
System.out.print("Guess again: ");
} else {
System.out.println("Too low.");
System.out.print("Guess again: ");
}
}
sc.close();
}
}
Ok so I've tried one method but it kept showing "Do you want to play again" every time i entered a number for some reason. Here is what I have so far. What else could i do to so that only after the user guesses the correct answer it asks if he/she wants to play again?
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int number = rand.nextInt(100) + 1;
int guess;
System.out.println("Guess the number between 1 and 100\n");
guess = scan.nextInt();
while (true) {
if(guess < number)
System.out.println("Higher!");
else if(guess > number)
System.out.println("Lower!");
else if (guess == number){
System.out.println("Correct!");
}
guess = scan.nextInt();
}
}
}
Try out this
class GuessNumber {
static Random rand = new Random();
static Scanner scan = new Scanner(System.in);
static int number;
public static void main(String[] args) {
playGame();
}
public static void playGame() {
number = rand.nextInt(100) + 1;
System.out.println("Guess the number between 1 and 100");
while (true) {
int guess = scan.nextInt();
if (guess < number) {
System.out.println("Higher!");
} else if (guess > number) {
System.out.println("Lower!");
} else if (guess == number) {
System.out.println("Correct!");
System.out.println("Do you like to play again?[1 for Yes/0 for No]");
int val = scan2.next();
if (val == 1)
playGame();
else
break;
}
}
}
}
or rather than using same scanner you can use another scanner and get string input as follows
else if (guess == number) {
System.out.println("Correct!");
Scanner scan2 = new Scanner(System.in);
System.out.println("Do you like to play again?[Y/N]");
String val = scan2.next();
if (val.equalsIgnoreCase("Y"))
playGame();
else
break;
}
You need to exit the while when correct.
To do so, after the line:
System.out.println("Correct!");
Add another line like this:
break;
Mostly out of fun, I implemented a game that fits the description of what you were trying to do. The code is not the cleanest / most efficient, but it definitely works!
Take a look at it and see if you can figure out your problem.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
System.out.println("Guess the number between 1 and 100");
playGuessingGame();
while (true) {
System.out
.println("Do you want to play again? Type y / n and hit enter");
Scanner scan = new Scanner(System.in);
String playAgain = scan.next();
if (playAgain.charAt(0) == 'y') {
System.out.println("Okay, I picked a new number. Good luck!");
playGuessingGame();
} else {
System.out.println("Thanks for playing!");
break;
}
}
}
public static void playGuessingGame() {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int guess;
int number = rand.nextInt(100) + 1;
guess = scan.nextInt();
while (guess != number) {
if (guess < number)
System.out.println("Higher!");
else if (guess > number)
System.out.println("Lower!");
else if (guess == number) {
System.out.println("Correct!");
}
guess = scan.nextInt();
}
}
}