user3340001
user3340001

Reputation: 237

Scanner failing at the very end of the input file

I have the following code:

    Scanner in = new Scanner(new FileReader("in.txt"));

    while(in.hasNext()){
        System.out.println(in.nextLine());
        System.out.println(in.nextLine());
        System.out.println(in.nextDouble());
        System.out.println(in.nextDouble());
        System.out.println(in.nextDouble());

        System.out.println(in.nextLine());
    }

Where in.txt is formatted as:

One Name
Second Name
double
double
double
One Name
Second Name
double
double
double
...

However, the while loop fails on the very last line in the input file. It prints the entire input file, but when it's done I get an error that says:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1585)
    at start.Start.main(Start.java:22)
Java Result: 1

Upvotes: 0

Views: 72

Answers (3)

Visruth
Visruth

Reputation: 3450

rewrite your code as follows, it will print all values

while(in.hasNext()){
        System.out.println(in.nextLine());
    }

Upvotes: 0

Sanjeev
Sanjeev

Reputation: 9946

As per your Input file the pattern is:

One Name
Second Name
double
double
double

so your while loop must match this pattern in order to read the file as

while(in.hasNext()){
    System.out.println(in.nextLine());
    System.out.println(in.nextLine());
    System.out.println(in.nextDouble());
    System.out.println(in.nextDouble());
    System.out.println(in.nextDouble());
}

For better handling of unusual cases you should use proper hasNextXXX() method before reading every line as suggested by @rendon.

Hope this helps.

Upvotes: 0

rendon
rendon

Reputation: 2363

The hasNext() method must be called every time before a reading because, in case of true, this method can guarantee that there is at least one more element to read. Your reading should look like this:

    if (in.hasNext())
        System.out.println(in.nextLine());
    if (in.hasNext())
        System.out.println(in.nextLine());
    if (in.hasNext())
        System.out.println(in.nextDouble());
    if (in.hasNext())
        System.out.println(in.nextDouble());
    if (in.hasNext())
        System.out.println(in.nextDouble());

    if (in.hasNext())
        System.out.println(in.nextLine());

Upvotes: 3

Related Questions