Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
50 lines (44 loc) · 1.42 KB

File metadata and controls

50 lines (44 loc) · 1.42 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package factorial;
import java.util.Scanner;
/**
* This program will print out the factorial of any non-negative
* number that you input into it.
*
* @author Marcus
*
*/
public class Factorial{
/**
* The main method
*
* @param args Command line arguments
*/
public static void main(String[] args){
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 || n == 1) return 1;
return n * factorial(n - 1);
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.