Sam Gregory
Sam Gregory

Reputation: 337

Recursion logic reading input

Hi I'm having some problem understanding why my recursion logic is returning the first input entered even though it does not seem to pass validation checks. A simple example in Java:

public class Main {

  public static void main(String[] args) {
    System.out.println(getInput(new Scanner(System.in)));
  }

  static private int getInput(Scanner scanner) { ;
    System.out.println("Give me input: ");
    int in = scanner.nextInt();
    if (in < 1 || in > 9) {
      getInput(scanner);
    }
    return in;
  }

}

My understanding is that the function should call itself until the condition is met and return a number between 0 and 9. The conditional check seems to work but whatever the first number is entered is always returned. An example execution yields:

Give me input: 
111
Give me input: 
222
Give me input: 
333
Give me input: 
444
Give me input: 
1
111

Upvotes: 0

Views: 83

Answers (2)

ryuzaki
ryuzaki

Reputation: 108

You may also want to revisit the need to use recursion for such use cases. To continuously ask users for valid inputs, recursion is overkill.

Think of use cases, when you want to limit cases, where users are abusing the system, with invalid inputs continuously, you would want to put an upper limit on the number of attempts.

An iterative solution is much simpler to understand, implement, and maintain.

Upvotes: 0

Buddy
Buddy

Reputation: 11038

When you are recursing, you are not storing the result of that call:

 getInput(scanner);

Should be:

 in = getInput(scanner);

Upvotes: 2

Related Questions