I have made a method to get the salary of a employee in java. This code takes the salary and checks whether the entered value is a Integer or not
static int askSalary(){
int s;
try {
s = sc.nextInt();
}catch (Exception e){
System.out.println("Not valid salary");
s = askSalary();
}
return s;
}
But the problem whenever a whenever a non - Integer value is entered in the first place the print statement in catch block keeps repeating. Can you tell me where I went wrong and the solution.
Thanks in advance
CodePudding user response:
The problem was, the way each of Scanner's method works. If you entered not-a-number input,nextInt()
will not consume that line, that is why you're getting infinite recursions. So to fix that, call next()
.
static int askSalary(){
int s;
try {
s = sc.nextInt();
}catch (Exception e){
System.out.println("Not valid salary");
sc.next(); //This will consume the previous line.
s = askSalary();
}
return s;
}
And your method can be improved like this:
static int askSalary() {
try {
return sc.nextInt();
}catch (Exception e){
System.out.println("Not valid salary");
sc.next();
return askSalary();
}
}
CodePudding user response:
It is repeating because you have created a loop.
When the operation askSalary()
cannot complete due to a problem, the catch block runs the operation again. This means that you will never stop attempting askSalary()
and since a programming problem seems to be present, it will never complete successfully.