1
+ package factorial ;
1
2
import java .util .Scanner ;
2
3
3
4
/**
4
5
* This program will print out the factorial of any non-negative
5
6
* number that you input into it.
6
7
*
7
- * @author Unknown
8
+ * @author Marcus
8
9
*
9
10
*/
10
11
public class Factorial {
@@ -15,39 +16,35 @@ public class Factorial{
15
16
* @param args Command line arguments
16
17
*/
17
18
public static void main (String [] args ){
18
- Scanner input = new Scanner (System .in );
19
- //Prompt user to enter integer
20
- System .out .print ("Enter a non-negative integer: " );
21
-
22
- //Proceed with factorial calculation only if inputted number is not negative
23
- if (input .hasNextInt ()){
24
- int number = input .nextInt ();
25
- if (number < 0 ){
26
- System .out .print ("Cannot execute. Please enter a non-negative integer: " );
27
- number = input .nextInt ();
28
- } else {
29
- //Output of factorial for any non-negative number
30
- System .out .println ("The factorial of " +number +" will yield: " +factorial (number ));
31
- }
32
- }
33
- input .close ();
34
- }
35
-
19
+ Scanner input = new Scanner (System .in );
20
+ System .out .print ("Enter a non-negative integer: " );
21
+
22
+ //If user does not enter an Integer, we want program to fail gracefully, letting the user know why it terminated
23
+ try {
24
+ int number = input .nextInt ();
25
+
26
+ //We keep prompting the user until they enter a positive number
27
+ while (number < 0 ){
28
+ System .out .println ("Your input must be non-negative. Please enter a positive number: " );
29
+ number = input .nextInt ();
30
+ }
31
+ //Display the result
32
+ System .out .println ("The factorial of " + number + " will yield: " + factorial (number ));
33
+
34
+ }catch (Exception e ){
35
+ System .out .println ("Error: You did not enter an integer. Program has terminated." );
36
+ }
37
+ input .close ();
38
+ }
39
+
36
40
/**
37
41
* Recursive Factorial Method
38
42
*
39
43
* @param n The number to factorial
40
44
* @return The factorial of the number
41
45
*/
42
46
public static long factorial (int n ){
43
-
44
- if (n ==0 ){
45
- return 1 ;
46
- } else if (n ==1 ){
47
- return 1 ;
48
- } else {
49
- return n * factorial (n -1 );
50
- }
51
-
47
+ if (n == 0 || n == 1 ) return 1 ;
48
+ return n * factorial (n - 1 );
52
49
}
53
- }
50
+ }
0 commit comments