Search code examples
javatry-catchgreatest-common-divisorlcm

Java: Program crashes after inputting two bad values


I coded a program, that calculates the gcd (greatest common divisor) and lcm (least common multiple). Everything works fine except the try {...} catch(...) {...}. Here is the part of the code that doesn't work as I want it to:

try {
    num1 = Integer.parseInt(sc.nextLine());
}
catch(Exception e) {
    System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
    System.out.print("Enter your first number: ");
    num1 = Integer.parseInt(sc.nextLine());
}

When I input e.g. letters, it says:

Your input is not an integer (number w/o decimals)! Try again.
Enter your first number:

But when I type letters the second time, the program crashes:

Exception in thread "main" java.lang.NumberFormatException: For input string: "asdf"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:658)
    at java.base/java.lang.Integer.parseInt(Integer.java:776)
    at GCDLCMgetter.main(GCDLCMgetter.java:56)

It is probably a very simple mistake I made but I can't figure it out...

Thank you


Solution

  • It's because your second prompt is inside the catch block. Instead of prompting again inside the catch block, you want to wrap the entire code section in a loop so it comes back around to the try block for the prompt again. Something like:

    boolean repeat = true;
    while(repeat){
        try{
            //Prompt for input
            repeat = false;
        }catch(Exception e) {
            //Display error message
        }
    }