Uh oh!
There was an error while loading. Please reload this page.
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
Latest commit
35 lines (29 loc) · 822 Bytes
/
Copy pathFactorial.java
File metadata and controls
35 lines (29 loc) · 822 Bytes
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
importjava.util.Scanner;
publicclassFactorial{
publicstaticvoidmain(String[] args){
Scannerinput = newScanner(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()){
intnumber = 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));
}
}
}
//Factorial method
publicstaticlongfactorial(intn){
if (n==0){
return1;
} elseif (n==1){
return1;
} else {
returnn * factorial(n-1);
}
}
}