Getting Factorial of a Number using Java (Source Code)

The following example will display the Factorial of a number using Java. This example shows also the try-catch of Java in catching exceptions.

Note: this is for demo only.

/*  From Techie.Click
    By JP  */
import java.util.Scanner;
public class FactorialSample {
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args) {
        try {
            System.out.println("This program will display the factorial of a number.");
            System.out.println("Enter a number: ");
            double num1 = input.nextDouble();
            double fac = 1;
            for(int i = 1; i <= num1;i++)
            {
                fac *= i;
            }
            System.out.println("Factorial is: " + fac);
        }
        catch(Exception e) {
            System.out.println("An error has occured. " + e);
        }
    }
}

Getting Factorial of a Number using Java (Source Code)

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.