Reputation: 47
Im constructing a program in which the user inputs a height between 3 and 10 and a triforce from zelda is printed in java. At the current moment, whenever the user inputs numbers outside that range an exception is thrown, however I want the program to throw an exception whenever any string is inputted. Im not sure how to utilise the InputMismatchException
. This is my code so far:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int height;
try {
System.out.print("Enter height: ");
height = keyboard.nextInt();
}
catch (InputMismatchException e) {
System.out.println("");
System.out.println("Invalid height.");
}
if (height < 3 || height > 10) {
System.out.println("Invalid height.");
System.exit(0);
}
Upvotes: 0
Views: 40
Reputation: 1346
try {
System.out.print("Enter height: ");
height = keyboard.nextInt();
if (height < 3 || height > 10) {
System.out.println("Invalid height.");
System.exit(0);
}
// print triforce from zelda
// ...
} catch (InputMismatchException e) {
System.out.println("please input a int");
}
Upvotes: 1