Asking user to input value between specific range recursively in JAVA?

2.7k Views Asked by At

I am writing a code in Java, where system will ask user to input integer between 1 and 10 (both Inclusive), and if the value is out of range, it should recursively ask the user to enter value again. And at the end I have to print the value which was within the range. Here below is my code:

`import java.util.Scanner; public class InputInteger {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Enter first Integer between 1 and 10 (both inclusive):");
    Scanner sc = new Scanner(System.in);
    int num1 = isInRange(sc, sc.nextInt());

    System.out.println("Enter Second Integer between 1 and 10 (both inclusive):");
    int num2 = isInRange(sc, sc.nextInt());

    System.out.println("Num 1 is "+num1+"\nNum 2 is "+num2);    
    sc.close();
}

public static int isInRange(Scanner scanner, int num) {
    if(num<1 || num>10) {
        System.out.println("WRONG INPUT. PLease enter Integer between 1 and 10 (both inclusive):");
        num =scanner.nextInt();
        isInRange(scanner, num);

    }
    return num;
}

}`

This will be my output: Output Image

The problem which I am facing is,when I am putting wrong values and ultimately when I put the right value, it will print the value which I entered at second time. Let's say I am putting 8 values which are out of range, and after that my 9th value is within range, so it will print the value which was entered at second time.

1

There are 1 best solutions below

4
On

You missed a little detail:

public static int isInRange(Scanner scanner, int num) {
                if(num<1 || num>10) {
                    System.out.println("WRONG INPUT. PLease enter Integer between 1 and 10 (both inclusive):");
                    num = scanner.nextInt();
                    num = isInRange(scanner, num); // add "num = " at the beginning of the line
                }
                return num;
            }

isInRange() returns an integer that you forgot to set to num.