import java.util.Scanner;
class recursion2 {
public static void main(String args[]) {
Scanner input1 = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
char cont = 'y';
while (cont == 'y') {
System.out.println("Enter the number:");
int num = scanner.nextInt();
int factorial = fact(num);
System.out.println("Factorial of entered number is: " + factorial);
System.out.println("Do you want to loop again?");
cont = input1.next().charAt(0);
}
}
static int fact(int n) {
int output;
if (n == 1) {
return 1;
}
output = fact(n - 1) * n;
return output;
}
}
The code above has 0 errors. However, Id like the code to only allow positive integers and if a user were to enter a negative integer (-20) or letters (abc) then the program would ask them to try again. I tried to use an If else statement saying if anything other than numbers > 0 would ask to try again but I could never make it work. Any tips?