techrawther
techrawther

Reputation: 183

Scanner Class Error

I am using Scanner class to read data from a file. The file content is displayed properly but at the end it is throwing java.util.NoSuchElementException error.What am I doing wrong here?

Following is the code.

Scanner sc_file=new Scanner(new File("/host/sha.txt")).useDelimiter("\n");
while (sc_file.hasNextLine())
{
    System.out.println(sc_file.next());

}


sc_file.close();

Error Stack

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:855)
    at java.util.Scanner.next(Scanner.java:1364)
    at basicjava.Input_output.main(Input_output.java:34)

Upvotes: 0

Views: 273

Answers (2)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You need to use \r\n as the delimiter:

.useDelimiter("\r\n");

Update:

hasNextLine()

Returns true if there is another line in the input of this scanner.

next()

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

So, basically what's happening is that for the last line hasNextLine() is returning true but somehow the last line does not seem to end with \n so it's not a complete token, which why next() is throwing NoSuchElementException.

You seem to be trying read the file line by line (as you are using \n as the delimiter for the next() method and hasNextLine() in your condition). So, I would recommend trying getting rid of the delimiter and using nextLine() instead of next():

scanner.nextLine();

Which would basically return the line disregarding whatever the line actually ends with.

Upvotes: 1

Umesh Rajbhandari
Umesh Rajbhandari

Reputation: 1282

I tested that myself. I also get the NoSuchElementException if the last line is empty. So the solution is not to have the empty line at the end. Note that setting .useDelimiter("\r\n") still caused the error.

Upvotes: 0

Related Questions