Paul D Paul D - 6 months ago 11
Java Question

Exception not being executed

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);
}

Answer
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");
}
Comments