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 :
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;
}
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;
}