Question

The docs say that NoSuchElementException is thrown when it tries to read past the last valid token . Keeping that in mind, if someone writes something like this :

while(scanner.next() !=null){
    // read string into your variable
}

where they assume that null will be returned as opposed to NoSuchElementException being thrown after reading past the last valid token , ( and so they don't keep any try-catch block ) will they be correct in doing so ?

EDIT: it turns out that i can use .hasNext() . Problem solved.

Was it helpful?

Solution

It is absolutely non-sensical to forbid using the hasNext() method.

That said, while breaking the "rules" of your question, you should be using the following idiom:

while (scanner.hasNext()) {
    String s = scanner.next();
    // do stuff...
}

If your situation is that you are curious, then sure, a NoSuchElementException will be thrown when there are no more tokens to be read. The only way to "check" this is a try-catch block. It will not return null in the case of an exception. Your program will simply die, provided you don't handle the exception...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top