I am learning Java and stumbled upon something I don't understand. Maybe someone can explain me why this code
Scanner sc = new Scanner("78438");
sc.hasNextInt();
sc.useDelimiter("4");
System.out.println(sc.nextInt());
has this output: 78438
I would expect it to be like the output of this
Scanner sc = new Scanner("78438");
sc.useDelimiter("4");
System.out.println(sc.nextInt());
or this
Scanner sc = new Scanner("78438");
sc.hasNextInt();
sc.useDelimiter("4");
sc.hasNextInt();
System.out.println(sc.nextInt());
or this code
Scanner sc = new Scanner("78438");
sc.useDelimiter("4");
sc.hasNextInt();
System.out.println(sc.nextInt());
which is: 78
Why is that, am I missing something? I thought the hasNextXXX() methods shouldn't have any effect on the state of the scanner...
hasNextInt method and other hasNext variants of Scanner cache the next token, so when you call nextInt after hasNextInt, it returns the cached result. You can have a look at the code of Scanner here: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/java/util/Scanner.java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With