Question: Exercise 5 - 2 Add validation to the Guess the Number application In this exercise, you'll add code that validates the user entries for the
Exercise Add validation to the Guess the Number application
In this exercise, you'll add code that validates the user entries for the Guess the Number application.
Open and test the project
Open the project named chexGuessNumber that's in the exstarts directory.
Open the GuessNumberApp.java file and review it's code. Note how the code in the main method calls the other method in the file.
Test the application to see how it works. When you do that, enter an invalid number like "five". Then, view the information that's printed to the console when the application crashes.
Validate the number that the user enters
In the while loop of the main method, code a try block around the statement that uses the parseInt method to get the number entered by the user. Then, code a catch block that catches the NumberFormatException. To get this to work, you need to declare the guess variable before the trycatch statement.
Add code to the catch block that displays an error message and uses a continue statement to jump the beginning of the while loop.
Test the application by entering an invalid number. When you do that, the application should display a userfriendly message and prompt you to try again.
Here is the default code that needs to be modified for this exercise:
import java.util.Scanner;
public class GuessNumberApp
private static void displayWelcomeint limit
System.out.printlnGuess the number!";
System.out.printlnIm thinking of a number from to limit;
System.out.println;
public static int getRandomIntint limit
double d Math.random limit; d is and limit
int i int d; convert double to int
i; int is and limit
return i;
public static void mainString args
final int LIMIT ;
displayWelcomeLIMIT;
int number getRandomIntLIMIT;
Scanner sc new ScannerSystemin;
int count ;
while true
System.out.printYour guess: ;
int guess Integer.parseIntscnextLine;
if guess guess LIMIT
System.out.printlnInvalid guess. Try again.";
continue;
if guess number
System.out.printlnToo low.";
else if guess number
System.out.printlnToo high.";
else
System.out.printlnYou guessed it in
count tries.
;
break;
count;
System.out.printlnBye;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
