Reputation: 35
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?
Upvotes: 2
Views: 170
Reputation: 79620
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char cont = 'y';
int num;
boolean valid;
String strNum;
do {
valid = false;
System.out.print("Enter the number: ");
strNum = scanner.nextLine();
if (strNum.matches("\\d+")) {
int factorial = fact(Integer.parseInt(strNum));
System.out.println("Factorial of entered number is: " + factorial);
System.out.print("Do you want to loop again?");
cont = scanner.nextLine().toLowerCase().charAt(0);
} else {
System.out.println("Invalid entry. Please try a positive integer.");
}
} while (cont == 'y');
System.out.println("Goodbye!");
}
static int fact(int n) {
int output;
if (n == 1) {
return 1;
}
output = fact(n - 1) * n;
return output;
}
}
A sample run:
Enter the number: a
Invalid entry. Please try a positive integer.
Enter the number: 10.5
Invalid entry. Please try a positive integer.
Enter the number: -5
Invalid entry. Please try a positive integer.
Enter the number: 5
Factorial of entered number is: 120
Do you want to loop again?y
Enter the number: 3
Factorial of entered number is: 6
Do you want to loop again?n
Goodbye!
Notes:
do...while
is more appropriate in this case. It doesn't mean that it can not be done using while
loop but do...while
makes it more comprehensible.scanner.nextLine().toLowerCase().charAt(0)
with y
so that the program can continue for both Y
and y
.\\d+
is used to restrict a string matching with only digits and nothing else i.e. it allows only intgers.Integer::parseInt
is used to convert an integer string into int
.Scanner
instances.class recursion2
should be named as class Recursion2
as per the naming convention.Upvotes: 2
Reputation: 868
Use this method to validate the input.
public int validInput() {
Scanner scanner = new Scanner(System.in);
while(1) {
// If you wish to end the loop after a certain number of attempts
// use a counter to exit the loop
System.out.println("Enter the number:");
int num = scanner.nextInt();
if(num > 0) {
return num;
}
System.out.println("Input must be greater than zero. Please try again.");
}
}
Then call this method from your code.
while (cont == 'y') {
int num = validInput();
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);
}
You can also use this method anywhere in your project.
Upvotes: 2
Reputation: 7604
To do this, you need a do-while loop where you check each time if the input is valid, and also a try-catch block inside the loop so if the Scanner throws an exception, you can catch it and ask the user to enter a positive number.
Also, you need to close the scanner at the end.
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 = -1; //Negative by default so it's invalid
do { //Do-while so it gets run at least once
try {
num = scanner.nextInt();
} catch (InputMismatchException e) { //When it's not an int, loop again
System.out.println("Please enter a valid input");
}
while (num <= 0); //Check if positive here
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);
}
scanner.close();
}
static int fact(int n)
{
int output;
if(n == 1){
return 1;
}
output = fact(n - 1) * n;
return output;
}
}
Upvotes: 1