Search code examples
javafactorial

How do I prevent an error message from repeating in Java?


I'm trying to write a program to calculate factorial but I can't figure out why the Error message displays twice if I enter a letter instead of an integer.
I feel like the issue has to do with Line 29 c = sc.next().charAt(0);, but am not sure how to fix it. Any help is appreciated.

My program:

public class Factorials {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        char c = 'Y';
        int num = 0;

        do
         {
            System.out.print("Enter a number to calculate its factorial: ");
            while (!sc.hasNextInt()) { 
                System.out.println("Invalid Entry - Enter only Integers! Try Again: ");
                sc.nextLine();
            }
            
            int result = 1;
            num = sc.nextInt();
            for(int i = 1; i <= num; i++) {
                result = result * i;
            }
            System.out.println("The factorial of " + num + " is: " + result);
            
            System.out.println("Do you wish to continue? Y/N: ");
            
            c = sc.next().charAt(0);
        }while(c == 'y' || c == 'Y');
        sc.close();
    }       
}

Solution

  • Simple fix: Change the sc.nextLine(); in your code to a sc.next() and you should be good to go. This error occurs because .nextLine() considers the enter/return key as a separate character, while .next() doesn't. (The enter key when you press it after entering either 'y' or 'n': if you try it, the error message doesn't print twice if you enter a letter the first time you run the program).

    Side note: You probably want it to be a .print(/*invalid input sentence*/) instead of a .println() to go along with how you take in your other number values.

    Otherwise, you're good!