SunnyX
asked on
core java. isInteger methods. Finding bug.
public static int isInputInteger(){
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
int correctNumber;
while(true){
input.nextLine();
if(input.hasNextInt()){
correctNumber = input.nextInt();
break;
}
else{
System.out.println("Your input isn't integer.Please, try again. ");
}
}
return correctNumber;
}
class PrintFromInput {
protected static int printNumber() {
System.out.printf("Please, enter integer: ");
int intYourConsoleInput = Assert.isInputInteger();
return intYourConsoleInput;
}
}
public class Task {
public static void main(String[] args) {
System.out.println("Congratulation! Your correct integer input is: "+ PrintFromInput.printNumber());
}
}
Inside class Assert there is a method "isInputInteger" everything work but not as I expect :
Session 1
input : f
output: {nothing }
input : f
output : Your input isn't integer.Please, try again.
input: g
output : Your input isn't integer.Please, try again.
input : 3
Congratulation! Your correct integer input is: 3
Session OVER
My question is why there isn't any message after first "f". Please, help me to find bug. Thx in advance !
At first glance, maybe because you are advancing the scanner too early.
why don'y you try setting breakpoints and debugging to find out what going on?
Remove this line :
input.nextLine();
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Yes, indeed. I thought the OP would be able to work out the required code move once he sees the result of just deleting it.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
The solution is :
Dear experts thx you so much for your help !
public static int onlyIntegerInput(){
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int correctNumber;
while (true){
if(!(scanner.hasNextInt())){
System.out.println("Your input isn't integer. Please, try again. ");
scanner.next();
continue;
}
else{
correctNumber = scanner.nextInt();
break;
}
}
return correctNumber;
}
Dear experts thx you so much for your help !
ASKER
Everybody many thanks !
Yes, that's it.