forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorial.java
More file actions
52 lines (46 loc) · 1.11 KB
/
Factorial.java
File metadata and controls
52 lines (46 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.Scanner;
/**
* This program will print out the factorial of any non-negative
* number that you input into it.
*
* @author Unknown
*
*/
public class Factorial{
/**
* The main method
*
* @param args Command line arguments
*/
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));
}
}
}
/**
* Recursive Factorial Method
*
* @param n The number to factorial
* @return The factorial of the number
*/
public static long factorial(int n){
if (n==0){
return 1;
} else if (n==1){
return 1;
} else {
return n * factorial(n-1);
}
}
}