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
  • 133,037
  • 18
  • 149
  • 215
Jason
  • 11,263
  • 21
  • 87
  • 181

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
  • 376,812
  • 128
  • 561
  • 623
3

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
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
  • 198,401
  • 62
  • 356
  • 264