Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Scanner > useDelimiter() in combination with hasNextInt() before and nextInt() after

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...

like image 604
user5242829 Avatar asked Dec 01 '25 16:12

user5242829


1 Answers

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

like image 128
uoyilmaz Avatar answered Dec 04 '25 07:12

uoyilmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!