Write a Java Program to accept a number from user and calculate the factorial of it. | EasyCoding45

Write a Java Program to accept a number from the user and calculate the factorial of it.


This program defines a Factorial class with a calculateFactorial method that uses recursion to calculate the factorial of a given number. The main method takes user input for a non-negative integer, calls the calculateFactorial method, and prints the result. The program also includes a check to handle negative input.

Program : (Write a Java Program to accept a number from the user and calculate the factorial of it.)

import java.util.Scanner;

public class Factorial {

    // Recursive method to calculate factorial

    static long calculateFactorial(int n) {

        if (n == 0 || n == 1) {

            return 1;

        } else {

            return n * calculateFactorial(n - 1);

        }

    }


    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);


        System.out.print("Enter a non-negative integer to calculate its factorial: ");

        int num = scanner.nextInt();


        if (num < 0) {

            System.out.println("Factorial is not defined for negative numbers.");

        } else {

            long factorial = calculateFactorial(num);

            System.out.println("Factorial of " + num + " is: " + factorial);

        }


        scanner.close();

    }

}


Output

https://easycoding45.blogspot.com/2023/11/write-java-program-to-accept-number.html

Comments