File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .Scanner ;
2+
3+ public class Factorial {
4+
5+ public static void main (String [] args ){
6+ Scanner input = new Scanner (System .in );
7+ //Prompt user to enter integer
8+ System .out .print ("Enter a non-negative integer: " );
9+
10+ //Proceed with factorial calculation only if inputted number is not negative
11+ if (input .hasNextInt ()){
12+ int number = input .nextInt ();
13+ if (number < 0 ){
14+ System .out .print ("Cannot execute. Please enter a non-negative integer: " );
15+ number = input .nextInt ();
16+ } else {
17+ //Output of factorial for any non-negative number
18+ System .out .println ("The factorial of " +number +" will yield: " +factorial (number ));
19+ }
20+ }
21+ }
22+
23+ //Factorial method
24+ public static long factorial (int n ){
25+
26+ if (n ==0 ){
27+ return 1 ;
28+ } else if (n ==1 ){
29+ return 1 ;
30+ } else {
31+ return n * factorial (n -1 );
32+ }
33+
34+ }
35+ }
You can’t perform that action at this time.
0 commit comments