views:

91

answers:

3

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?

+7  A: 

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
polygenelubricants
your answer helped me the most, particularly the second link. Thanks!
Jason
+3  A: 

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

Bozho
This is basically what I wanted to know, what argument to use inside the parenthesis to call the main method.
Jason
the one that has been passed to the main method - the `String[] args`
Bozho
And of course, unlike a loop, this can only happen so many times before it `StackOverflowError`.
polygenelubricants
A: 

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