Search code examples
javafor-loopif-statementfactorial

How to create error message when negative number is entered in Java factorial


I need to modify this code so that and error message is displayed when a negative number is entered. I know and else statement has to fit in I just can figure out where.


Solution

  • I guess all you need to do is check for incorrect input to throw an exception.

    public static void numberFactorial() {  
        System.out.println("Option 2 selected, enter a number: "); 
        int number = sc.nextInt(); 
        if(number < 0){
             throw new IllegalArgumentException()
        }
        // ... rest of the code
    }