I need explanation about how does scanner's hasNextInt()
works. In next example:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean foo = sc.hasNextBoolean();
System.out.println(sc.nextLine());
}
when program gets to hasNextBoolean()
, it waits for my input. Then I press Enter for newline and type true and press Enter again,so the buffer looks like this: [ \n true \n ].
Now the pointer is on word true, and so foo becomes true. But then, the pointer should still be hanging on true, and when next line comes, program should print true, but what happens is that it just prints newline. Why is that case, may I ask?
On the other hand, doing same thing but using nextInt(), works the way that i expected:
public static void main(String[] args) {
Scanner skener = new Scanner(System.in);
try{
int stagod = skener.nextInt();}
catch(Exception e){
System.out.println(skener.nextLine());}
}
Here when program come to skener.nextInt()
, I press Enter then type A then press Enter, so the buffer looks like this: [ \n A \n ].
And now, after catching the exception, pointer stays on A and System.out.println(skener.nextLine());
prints A.