-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathFactorialCalculator.java
More file actions
33 lines (28 loc) · 1004 Bytes
/
FactorialCalculator.java
File metadata and controls
33 lines (28 loc) · 1004 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
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
scanner.close();
long factorial = calculateFactorial(number);
if (factorial != -1) {
System.out.println("Factorial of " + number + " is: " + factorial);
} else {
System.out.println("Factorial is not defined for negative numbers.");
}
}
public static long calculateFactorial(int n) {
if (n < 0) {
return -1; // Factorial is not defined for negative numbers
} else if (n == 0) {
return 1; // The factorial of 0 is defined as 1
} else {
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
}