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 5-2 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
1. Open the project named ch05_ex2_GuessNumber that's in the ex_starts directory.
2. 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.
3. 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
4. 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 try/catch statement.
5. Add code to the catch block that displays an error message and uses a continue statement to jump the beginning of the while loop.
6. Test the application by entering an invalid number. When you do that, the application should display a user-friendly 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 displayWelcome(int limit){
System.out.println("Guess the number!");
System.out.println("I'm thinking of a number from 1 to "+ limit);
System.out.println();
}
public static int getRandomInt(int limit){
double d = Math.random()* limit; // d is >=0.0 and < limit
int i =(int) d; // convert double to int
i++; // int is >=1 and <= limit
return i;
}
public static void main(String[] args){
final int LIMIT =10;
displayWelcome(LIMIT);
int number = getRandomInt(LIMIT);
Scanner sc = new Scanner(System.in);
int count =1;
while (true){
System.out.print("Your guess: ");
int guess = Integer.parseInt(sc.nextLine());
if (guess <1|| guess > LIMIT){
System.out.println("Invalid guess. Try again.");
continue;
}
if (guess < number){
System.out.println("Too low.");
} else if (guess > number){
System.out.println("Too high.");
} else {
System.out.println("You guessed it in "+
count +" tries.
");
break;
}
count++;
}
System.out.println("Bye!");
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!