Skip to content

Commit 5427f0d

Browse files
Merge pull request #12 from anthonyc1/master
Implement factorial
2 parents bbc9f0d + 3147226 commit 5427f0d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Factorial.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.Scanner;
2+
3+
public class Factorial{
4+
5+
public static void main(String[] args){
6+
Scanner input = new Scanner(System.in);
7+
//Prompt user to enter integer
8+
System.out.print("Enter a non-negative integer: ");
9+
10+
//Proceed with factorial calculation only if inputted number is not negative
11+
if(input.hasNextInt()){
12+
int number = input.nextInt();
13+
if (number < 0){
14+
System.out.print("Cannot execute. Please enter a non-negative integer: ");
15+
number = input.nextInt();
16+
} else {
17+
//Output of factorial for any non-negative number
18+
System.out.println("The factorial of "+number+" will yield: "+factorial(number));
19+
}
20+
}
21+
}
22+
23+
//Factorial method
24+
public static long factorial(int n){
25+
26+
if (n==0){
27+
return 1;
28+
} else if (n==1){
29+
return 1;
30+
} else {
31+
return n * factorial(n-1);
32+
}
33+
34+
}
35+
}

0 commit comments

Comments
 (0)