Skip to content

Commit 149e5d2

Browse files
authored
Update Factorial.java
The factorial method can be simplified to 2 lines, which I believe is easier to read. Also, in previous version, if user enters two negative numbers back to back, the program crashes. We need a while loop to prompt the user until they actually enter the correct input, instead of only prompting them once. Also, if user enters a character instead of an integer, program crashes with no error message. We should fail more gracefully.
1 parent 3907716 commit 149e5d2

File tree

1 file changed

+26
-29
lines changed

1 file changed

+26
-29
lines changed

Factorial.java

Lines changed: 26 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
package factorial;
12
import java.util.Scanner;
23

34
/**
45
* This program will print out the factorial of any non-negative
56
* number that you input into it.
67
*
7-
* @author Unknown
8+
* @author Marcus
89
*
910
*/
1011
public class Factorial{
@@ -15,39 +16,35 @@ public class Factorial{
1516
* @param args Command line arguments
1617
*/
1718
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+
3640
/**
3741
* Recursive Factorial Method
3842
*
3943
* @param n The number to factorial
4044
* @return The factorial of the number
4145
*/
4246
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);
5249
}
53-
}
50+
}

0 commit comments

Comments
 (0)