I’m working on a Serpinski triangle program that asks the user for the levels of triangles to draw. In the interests of idiot-proofing my program, I put this in:
Scanner input= new Scanner(System.in);
System.out.println(msg);
try {
level= input.nextInt();
} catch (Exception e) {
System.out.print(warning);
//restart main method
}
Is it possible, if the user punches in a letter or symbol, to restart the main method after the exception has been caught?
You can prevent the
Scannerfrom throwingInputMismatchExceptionby usinghasNextInt():This is an often forgotten fact: you can always prevent a
Scannerfrom throwingInputMismatchExceptiononnextXXX()by first ensuringhasNextXXX().But to answer your question, yes, you can invoke
main(String[])just like any other method.See also
Note: to use
hasNextXXX()in a loop, you have to skip past the “garbage” input that causes it to returnfalse. You can do this by, say, calling and discardingnextLine().