Where to put exception for Java Guessing Game - java

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");

Related

How do I add a limit to the number of guesses in a number guessing game?

I cannot figure out how to add a limit to the number of guesses in my number guessing game. I have tried adding a for statement after the while statement but that made the code just stop at the tenth guess and there was no winner ever. I deleted the while statement and just did the for statement which ensured that the user got the correct answer every ninth guess. My code is divided into two classes as requested by my professor. I am including both below. I would appreciate all the help I can get. Thank you!
GuessingGame.java: Main Class
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while(!win) {
System.out.println("You are limited to ten attempts."
+ "Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (guess > 1000 ) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount -1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount -1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " +answer);
System.out.println("It took you " + tries + " tries");
}
}
You can add an if-statement inside the while loop.
public void doGuess() {
while(!win) {
System.out.println("You are limited to ten attempts."
+ "Guess a number between 1 and 1000: ");
guess = input.nextInt();
if(tries > 9) {
...whatever you want to happen when user has reached 10 guesses...
}

Returning to the start of the Program

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

Random # Guessing Game Infinite Loop

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

Java guess game. How do I use data validation to check if a number is within a certain range?

I need help coding a set of statements of data validation that checks if a user entry is within a range of 0 and 100, and anything the user types that ISNT a non-decimal integer between 1 and 100 should display an error message. Also I need a way to code how I can get a "goodbye" output to only display if the user enters "n" not "n" and "y." N meaning no and y meaning yes.
Heres my code.
import java.util.Scanner;
public class GuessingGameCalc {
private static void displayWelcomeMessage(int max) {
System.out.println("Welome to the Java Guessing Game!");
System.out.println(" ");
System.out.println("I'm thinking of a number between 1 and" + " " + max + " " + "let's see if you guess what it is!");
System.out.println(" ");
}
public static int calculateRandomValue(int max) {
double value = (int) (Math.random() * max + 1);
int number = (int) value;
number++;
return number;
}
public static void validateTheData(int count) {
if( count < 3) {
System.out.println("Good job!");
} else if (count < 7) {
System.out.println("Need more practice.");
} else{
System.out.println("Need way more practice.");
}
}
public static void main(String[] args) {
final int max = 100;
String prompt = "y";
displayWelcomeMessage(max);
int unit = calculateRandomValue(max);
Scanner sc = new Scanner(System.in);
int counter = 1;
while (prompt.equalsIgnoreCase("y")) {
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
if ( (unit - userEntry) > 10 ) {
System.out.println("Way Too low! Guess higher!");
} else {
System.out.println("Too low! Guess higher!");
}
} else if (userEntry > unit) {
if( (userEntry - unit) > 10 ){
System.out.println("Way Too high! Guess lower!");
} else {
System.out.println("Too high! Guess lower!");
}
} else {
System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
validateTheData(counter);
break;
}
counter++;
}
System.out.println("Would you like to try again? Yes or No?");
prompt = sc.next();
System.out.println("Goodbye!");
}
}
}
Instead of using .nextInt() rather use .nextLine(), which returns a String and then parse it to an int and catch the NumberFormatException
So basically you'll have this structure:
try {
int userEntry = Integer.parseInt(sc.nextLine());
...
} catch (NumberFormatException nfe) {
System.out.println("Please enter a valid number.");
}
Oh, just a comment on the rest of your code. You don't really need two while loops, one will be more than sufficient.

InputMismatchException for guess number

I am doing a guessing game where in I can input 1-100 but I am having a trouble in only accepting numbers if I typed a letter when I first run the program it will give me error and execute the program instantly image herebut if ityped number after I start the program and type letter next it give me a wrong message it should only display message saying "invalid input".image here Any suggestion thanks.
package m1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class M1{
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int between = 100;
int secretNumber = (int)(Math.random()*between);
int inputNum = 0;
int guesses = 0;
System.out.println("Please enter your guess: ");
inputNum = Scanner.nextInt();
guesses++;
while (inputNum != secretNumber) {
try {
// number too high or too low
if (inputNum > 100 || inputNum < 1) {
System.out.println("Out of Range!");
System.out.println("Enter a guess between 1 and " + between + ".");
inputNum = Scanner.nextInt();
}
// less than secretNumber
if (inputNum < secretNumber) {
System.out.println("Too Low...Try Again!");
inputNum = Scanner.nextInt();
guesses++;
}
// greater than secretNumber
if (inputNum > secretNumber) {
System.out.println("Too High...Try Again!");
inputNum = Scanner.nextInt();
guesses++;
}
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
Scanner.next();
}
}
System.out.println("\nWell done! The secret number was " + secretNumber + "." + "\nYou took " + guesses + " guesses.");
}
}
Generally, name variable names in java using camelCase in most cases.
You don't actually need to catch any exception in your case as you can simply do scanner.next() if scanner.hasNextInt() is false. Prompting the user to enter specifically a number this time.
Try the below code:
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
class Main {
private static final String GUESS_PROMPT_PATTERN = "Please enter a guess between %d and %d inclusive: ";
private static final String WIN_PROMPT_PATTERN = "Well done! The secret number was %d. You took %d guesses.\n";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minimumGuess = 1, maximumGuess = 100;
int secretNumber = ThreadLocalRandom.current().nextInt(minimumGuess, maximumGuess + 1);
int guesses = 0;
String guessPrompt = String.format(GUESS_PROMPT_PATTERN, minimumGuess, maximumGuess);
System.out.println("Lec's Guessing Game");
System.out.println("====================");
System.out.print(guessPrompt);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
guesses++;
int inputNum = scanner.nextInt();
if (inputNum == secretNumber) {
break;
}
// Input number too high or too low.
if (inputNum > maximumGuess || inputNum < minimumGuess) {
System.out.println("Out of Range!");
scanner.nextLine();
System.out.print(guessPrompt);
}
// Input number was less than the secret number.
else if (inputNum < secretNumber) {
System.out.println("Too Low... Try Again!");
System.out.print(guessPrompt);
}
// Input number was greater than the secret number.
else {
System.out.println("Too High... Try Again!");
System.out.print(guessPrompt);
}
} else {
System.out.print("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
System.out.printf(WIN_PROMPT_PATTERN, secretNumber, guesses);
}
}

Categories

Resources