Upload fact.txt
Browse files
fact.txt
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import java.util.Scanner;
|
2 |
+
|
3 |
+
public class FactorialCalculator {
|
4 |
+
|
5 |
+
public static void main(String[] args) {
|
6 |
+
// Create a Scanner object for user input
|
7 |
+
Scanner scanner = new Scanner(System.in);
|
8 |
+
|
9 |
+
System.out.print("Enter a non-negative integer: ");
|
10 |
+
|
11 |
+
// Validate user input
|
12 |
+
if (!scanner.hasNextInt()) {
|
13 |
+
System.out.println("Invalid input. Please enter a valid integer.");
|
14 |
+
scanner.close();
|
15 |
+
return;
|
16 |
+
}
|
17 |
+
|
18 |
+
int number = scanner.nextInt();
|
19 |
+
|
20 |
+
// Check if the number is non-negative
|
21 |
+
if (number < 0) {
|
22 |
+
System.out.println("Factorial is not defined for negative numbers.");
|
23 |
+
} else {
|
24 |
+
// Calculate factorial
|
25 |
+
long factorial = 1; // Use long to handle large results
|
26 |
+
for (int i = 1; i <= number; i++) {
|
27 |
+
factorial *= i;
|
28 |
+
}
|
29 |
+
|
30 |
+
// Display the result
|
31 |
+
System.out.println("The factorial of " + number + " is: " + factorial);
|
32 |
+
}
|
33 |
+
|
34 |
+
// Close the scanner
|
35 |
+
scanner.close();
|
36 |
+
}
|
37 |
+
}
|
38 |
+
|
39 |
+
confidential file.
|