Write a Java program that calculates the factorial of a given non-negative integer.

import java.util.Scanner;

public class FactorialCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a non-negative integer: ");
        
        int n = scanner.nextInt();
        
        if (n < 0) {
            System.out.println("Please enter a non-negative integer.");
        } else {
            long factorial = calculateFactorial(n);
            System.out.println("Factorial of " + n + " is: " + factorial);
        }
        
        scanner.close();
    }

    // Function to calculate factorial
    private static long calculateFactorial(int num) {
        if (num == 0 || num == 1) {
            return 1;
        } else {
            return num * calculateFactorial(num - 1);
        }
    }
}
  • The program takes a non-negative integer as input from the user.
  • It checks if the input is non-negative. If not, it prompts the user to enter a non-negative integer.
  • The calculateFactorial function is a recursive function that calculates the factorial of a given number.
  • The result is then printed to the console.

Post your Answer