HasNext Methods

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        
10 12
13 4 6 0
-2
rats

Answer:

Yes.

HasNext Methods

When the "rats" is encountered, hasNextInt() will return false and the loop (and program) will end gracefully. (The phrase "end gracefully" is what programmers say when they mean that a program ends as intened, not an unintended crash accompanied by error messages.)

There are several hasNext methods that are usually used along with their corresponding next methods. The table shows several:

Methods of Scanner
HasNext MethodReading Method
hasNext() next()
hasNextDouble() nextDouble()
hasNextFloat() nextFloat()
hasNextInt() nextInt()
hasNextLine() nextLine()
hasNextLong() nextLong()

Usually your programs will use the methods for int and double, and the hasNext() and next() methods. These last two methods work with tokens which are groups of any characters delimited (surrounded) by one or more spaces.

QUESTION 8:

Does calling a hasNext() method consume any data from the file?