The program shall:
• generate a random number from 1 to 50 for a player to guess;
• display a message that indicates whether the player's guess is correct, too low, or too high; • prompt the user to keep on guessing until the correct value is entered
4. Create a try-catch structure that will handle two (2) exceptions. These are when the user inputs the following:
• a number that is out of range (1 - 50) a letter or any non-numeric character
5. Prompt the user so that he can guess again if an exception is thrown.
6. Display the number of total guesses.
Note: An invalid input (when an exception is thrown) is not considered a valid guess or attempt.
Sample Output:
Guess a number from 1 to 50!
30
Too high. Try Again.
10
Too high. Try again
qwerty
Invalid input.
Guess a number from 1 to 50!
51
Out of range.
Guess a number from 1 to 50!
1
Too low. Try Again.
import java.util.Random;
import java.util.Scanner;
class OutRange extends Exception {
public OutRange(String msg) {
super(msg);
}
}
public class App {
public static void main(String[] args) throws OutRange {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int attempts = 0;
int randomValue = rand.nextInt(50) + 1;
int userValue = -1;
while (userValue != randomValue) {
try {
try {
System.out.println("Guess a number from 1 to 50!");
userValue = input.nextInt();
if (userValue < 1 || userValue > 50) {
throw new OutRange("Too high. Try Again.");
}
if (userValue > randomValue) {
System.out.println("Too high. Try Again.");
}
if (userValue < randomValue) {
System.out.println("Too low. Try Again.");
}
} catch (OutRange e) {
System.out.println("Out of range.");
}
} catch (Exception e) {
System.out.println("Invalid input.");
input.next();
}
attempts++;
}
System.out.println("Correct.\nThe number of total guesses: " + attempts + ".");
input.close();
}
}
Comments
Leave a comment