1. In Chapter 1, you created a class called RandomGuess. In this game, the appli
ID: 3676187 • Letter: 1
Question
1. In Chapter 1, you created a class called RandomGuess. In this game, the application generates a random number
for a player to guess. In Chapter 5, you improved the application to display a message indicating whether the
player’s guess was correct,too high, or too low. In Chapter 6, you further improved the game by adding a
loop that continually prompts the user to enter the correct value, if necessary. As written,the game
should work as long as the player enters numeric guesses. However, if the player enters a letter or
other non numeric character, the game throws an exception.Discover the type of Exception thrown, then
improve the game by handling the exception so that the user is informed of the error and allowed
to attempt to enter the correct data again. Save the file as RandomGuess4.java
Explanation / Answer
import java.util.Random;
import java.util.Scanner;
public class RandomGuess {
public static void main(String[] args) {
// Create a random number generator
Random random = new Random();
// Use Scanner for getting input from user
Scanner scanner = new Scanner(System.in);
// Use the random generator to
// pick a number between 0 and 99 (inclusive)
int number = random.nextInt(100);
int guess = -1;
// Loop until the user has guessed the number
while (guess!=number) {
// Prompt the user for their next guess
System.out.print("Enter your guess: ");
// Read the users guess
guess = scanner.nextInt();
// Check if the guess is high, low or correct
if (guess<number) {
// Guess is too low
System.out.println("Too low, please try again");
} else if (guess>number) {
// Guess is too high
System.out.println("Too high, please try again");
} else {
// Guess is correct !!
System.out.println("Correct, the number was " + number);
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.