1

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?

Donal Fellows
  • 120,022
  • 18
  • 134
  • 199
Jason
  • 10,777
  • 19
  • 81
  • 169

3 Answers3

8

You can prevent the Scanner from throwing InputMismatchException by using hasNextInt():

if (input.hasNextInt()) {
   level = input.nextInt();
   ...
}

This is an often forgotten fact: you can always prevent a Scanner from throwing InputMismatchException on nextXXX() by first ensuring hasNextXXX().

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 return false. You can do this by, say, calling and discarding nextLine().

    Scanner sc = new Scanner(System.in);
    while (!sc.hasNextInt()) {
        System.out.println("int, please!");
        sc.nextLine(); // discard!
    }
    int i = sc.nextInt(); // guaranteed not to throw InputMismatchException
Community
  • 1
  • 1
polygenelubricants
  • 348,637
  • 121
  • 546
  • 611
3

Well, you can call it recursively: main(args), but you'd better use a while loop.

Bozho
  • 554,002
  • 136
  • 1,025
  • 1,121
0

You much better want to do this:

boolean loop = true;
Scanner input= new Scanner(System.in);
System.out.println(msg);
do{
    try {
        level= input.nextInt();
        loop = false;
    } catch (Exception e) {
        System.out.print(warning);
        //restart main method
        loop = true;
    }
while(loop);
Cristian
  • 191,931
  • 60
  • 351
  • 260