This is guessing game program import java.util.Scanner; public class GuessingGam
ID: 3570051 • Letter: T
Question
This is guessing game program
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
int secretNumber=12;
int guess;
do{
System.out.println("Please enter a number ");
guess=keyboard.nextInt();
if (guess>12){
System.out.println("your guess is too high");
}
else if(guess<12){
System.out.println("Your guess is too low");
}
else{
System.out.println("congratuatlation! YOur guess is correct");
}
}while (!(guess==secretNumber));
}
}
Now Rewrite thsi Guessing Game program from above to use Exceptions to handle invalid guesses. (You can also write a new version of the whole program.)
Specifically, once the user enters a guess, you should throw an exception if the guess is out of range. i.e. if the user is told to guess a number between 1 and 100, but enters 1001, then the code should thrown an exception with a helpful error message. Your code should also throw an exception if the user input is invalid (i.e. they enter a word instead of a number).
Your code should also catch the above Exceptions, show the user an error message, and ask the user to re-enter their guess.
Hint: One way to do this is to write a helper method which asks the user for their guess, and either returns a valid guess or throws an Exception. You can then call this helper method from your main method, using a try-catch block to handle any Exceptions.
part b
Currently you are handling errors in your To do list program by printing an error mesage to the screen and exiting. Instead, have any method that catches an error in this fashion instead throw an Exception. Catch all Exceptions in your main method.
Explanation / Answer
import java.util.Random; import java.util.Scanner; public class GuessingGame { public static void main(String[] args) { Random rand = new Random(); int TAL = rand.nextInt(20) + 1; int FORS
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.