Skip to content

Update Factorial.java #52

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 1, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 26 additions & 29 deletions Factorial.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package factorial;
import java.util.Scanner;

/**
* This program will print out the factorial of any non-negative
* number that you input into it.
*
* @author Unknown
* @author Marcus
*
*/
public class Factorial{
Expand All @@ -15,39 +16,35 @@ public class Factorial{
* @param args Command line arguments
*/
public static void main(String[] args){
Scanner input = new Scanner(System.in);
//Prompt user to enter integer
System.out.print("Enter a non-negative integer: ");

//Proceed with factorial calculation only if inputted number is not negative
if(input.hasNextInt()){
int number = input.nextInt();
if (number < 0){
System.out.print("Cannot execute. Please enter a non-negative integer: ");
number = input.nextInt();
} else {
//Output of factorial for any non-negative number
System.out.println("The factorial of "+number+" will yield: "+factorial(number));
}
}
input.close();
}

Scanner input = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");

//If user does not enter an Integer, we want program to fail gracefully, letting the user know why it terminated
try{
int number = input.nextInt();

//We keep prompting the user until they enter a positive number
while(number < 0){
System.out.println("Your input must be non-negative. Please enter a positive number: ");
number = input.nextInt();
}
//Display the result
System.out.println("The factorial of " + number + " will yield: " + factorial(number));

}catch(Exception e){
System.out.println("Error: You did not enter an integer. Program has terminated.");
}
input.close();
}

/**
* Recursive Factorial Method
*
* @param n The number to factorial
* @return The factorial of the number
*/
public static long factorial(int n){

if (n==0){
return 1;
} else if (n==1){
return 1;
} else {
return n * factorial(n-1);
}

if(n == 0 || n == 1) return 1;
return n * factorial(n - 1);
}
}
}