If I understood you correctly, you want the program to ask the user to re-enter a right input after it fails. In that case you can do something like:
boolean inputOk = false;
while (!inputOk) {
System.out.print("Define width: ");
try {
width = scanner.nextDouble();
inputOk = true;
} catch (InputMismatchException e) {
System.err.println("That's not a number!");
scanner.nextLine(); // This discards input up to the
// end of line
// Alternative for Java 1.6 and later
// scanner.reset();
}
}
Note: you should only catch and retry for a InputMismatchException
. The nextXxx
methods throw other exceptions, and if you attempt to retry those, your application will go into an infinite loop.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…