Search code examples
javacallbackuser-input

Controlling user input with callback functions in Java


First of all I am totally new to Java and trying to understand POO.

Presentation :

In a class, I defined a method called inputCapacity. I would like my user to enter a number between 1 to 4. In a way to verify, I tried to implement a little condition.

Problem : When the User make a mistake, the function loops well, but the userResponse returned correspond to the first input! Where do I need to re-assign my variable ?

Precisions :

  • Java 13
  • console App
static int inputCapacity() {
    Scanner in = new Scanner(System.in);
    System.out.println("Indiquez le nombre de personnes (max 4) : ");
    int userResponse = in.nextInt();
    if (userResponse < 1 || userResponse > 4) {
    System.out.println("Saisissez un nombre valide (max 4).");
    inputCapacity();
    }
      return userResponse;
}


Solution

  • When you call inputCapacity() the second time, the result from that second invocation is ignored. Simply adding a return statement before the call should fix your problem.

    static int inputCapacity() {
        Scanner in = new Scanner(System.in);
        System.out.println("Indiquez le nombre de personnes (max 4) : ");
        int userResponse = in.nextInt();
        if (userResponse < 1 || userResponse > 4) {
          System.out.println("Saisissez un nombre valide (max 4).");
          return inputCapacity();
        }
        return userResponse;
    }