For a project in school, I am attempting to use the try/catch to prevent the program from crashing when the user enters a letter instead of the desired input type (i.e. a double).
public static double inputSide () {
Scanner in = new Scanner(System.in);
double side = -1;
do {
try {
System.out.println("Enter a side length (in units):");
side = in.nextDouble();
}
catch(InputMismatchException e){
System.out.println("Must input number");
}
} while (side < 0);
return side;
}
When I execute this code, it gets stuck in a loop where it outputs "Enter a side length (in units): " and "Must input number" infinitely. I am new to using try/catch, so I perhaps am simply unfamiliar with this behaviour. Anyway, if someone can help me figure out the problem, it would be much appreciated. Thanks in advance.