2017-03-16 22:39:23 +08:00
|
|
|
import java.util.Scanner;
|
|
|
|
|
2017-04-18 22:57:17 +08:00
|
|
|
/**
|
|
|
|
* This program will print out the factorial of any non-negative
|
|
|
|
* number that you input into it.
|
|
|
|
*
|
|
|
|
* @author Unknown
|
|
|
|
*
|
|
|
|
*/
|
2017-03-16 22:39:23 +08:00
|
|
|
public class Factorial{
|
|
|
|
|
2017-04-18 22:57:17 +08:00
|
|
|
/**
|
|
|
|
* The main method
|
|
|
|
*
|
|
|
|
* @param args Command line arguments
|
|
|
|
*/
|
2017-03-16 22:39:23 +08:00
|
|
|
public static void main(String[] args){
|
|
|
|
Scanner input = new Scanner(System.in);
|
|
|
|
//Prompt user to enter integer
|
|
|
|
System.out.print("Enter a non-negative integer: ");
|
|
|
|
|
|
|
|
//Proceed with factorial calculation only if inputted number is not negative
|
|
|
|
if(input.hasNextInt()){
|
|
|
|
int number = input.nextInt();
|
|
|
|
if (number < 0){
|
|
|
|
System.out.print("Cannot execute. Please enter a non-negative integer: ");
|
|
|
|
number = input.nextInt();
|
|
|
|
} else {
|
|
|
|
//Output of factorial for any non-negative number
|
|
|
|
System.out.println("The factorial of "+number+" will yield: "+factorial(number));
|
|
|
|
}
|
2017-04-21 02:56:21 +08:00
|
|
|
}
|
|
|
|
input.close();
|
2017-03-16 22:39:23 +08:00
|
|
|
}
|
|
|
|
|
2017-04-18 22:57:17 +08:00
|
|
|
/**
|
|
|
|
* Recursive Factorial Method
|
|
|
|
*
|
|
|
|
* @param n The number to factorial
|
|
|
|
* @return The factorial of the number
|
|
|
|
*/
|
2017-03-16 22:39:23 +08:00
|
|
|
public static long factorial(int n){
|
|
|
|
|
|
|
|
if (n==0){
|
|
|
|
return 1;
|
|
|
|
} else if (n==1){
|
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
return n * factorial(n-1);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|