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.
|
|
|
|
*
|
2017-06-01 07:38:17 +08:00
|
|
|
* @author Marcus
|
2017-04-18 22:57:17 +08:00
|
|
|
*
|
|
|
|
*/
|
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){
|
2017-06-01 07:38:17 +08:00
|
|
|
Scanner input = new Scanner(System.in);
|
|
|
|
System.out.print("Enter a non-negative integer: ");
|
|
|
|
|
|
|
|
//If user does not enter an Integer, we want program to fail gracefully, letting the user know why it terminated
|
|
|
|
try{
|
|
|
|
int number = input.nextInt();
|
|
|
|
|
|
|
|
//We keep prompting the user until they enter a positive number
|
|
|
|
while(number < 0){
|
|
|
|
System.out.println("Your input must be non-negative. Please enter a positive number: ");
|
|
|
|
number = input.nextInt();
|
|
|
|
}
|
|
|
|
//Display the result
|
|
|
|
System.out.println("The factorial of " + number + " will yield: " + factorial(number));
|
|
|
|
|
|
|
|
}catch(Exception e){
|
|
|
|
System.out.println("Error: You did not enter an integer. Program has terminated.");
|
|
|
|
}
|
|
|
|
input.close();
|
|
|
|
}
|
|
|
|
|
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){
|
2017-06-01 07:38:17 +08:00
|
|
|
if(n == 0 || n == 1) return 1;
|
|
|
|
return n * factorial(n - 1);
|
2017-03-16 22:39:23 +08:00
|
|
|
}
|
2017-06-01 07:38:17 +08:00
|
|
|
}
|