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;
}
}`
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.
You missed a little detail:
isInRange() returns an integer that you forgot to set to num.