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.
import java.nio.charset.MalformedInputException;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Random rand = new Random();
int che = rand.nextInt(51);
int v = 0;
do {
System.out.print("Enter number: ");
v = in.nextInt();
try {
if(0 > v & v > 50)
throw new IllegalArgumentException();
} catch (IllegalArgumentException e){
System.out.println("Input error!");
continue;
} catch (InputMismatchException e){
System.out.println("Input error!");
continue;
}
if(v > che)
System.out.println("your number is higher");
if(v < che)
System.out.println("your number is less");
}while(v!=che);
System.out.println("Win");
}
}
Comments
Leave a comment