Th3Nic3Guy
Th3Nic3Guy

Reputation: 1979

java.util.NoSuchElementException: No line found when line exists in file

I have a Code where I am scanning the lines using Scanner Class and looping till there are no lines left.

My code looks like this:

File file = new File(filePath);

if (file.exists()) {
    Scanner s = new Scanner(file);
    String tmp = null;
    int result = 0;
    try {
        while (true) {
            tmp = s.nextLine();
            if (tmp != null && tmp.equals("")) {
                result += Integer.parseInt(tmp);
            }
            System.out.println(runSequence(Integer.parseInt(tokens[0])));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(result);
}

It gives the error at

tmp = s.nextLine();

java.util.NoSuchElementException: No line found

Which is odd because earlier the same code was working fine.

Why is this line giving an error?

Edit:

My mistake i did not state the question correctly, i particularly left the try catch block out of the while loop so that i could make an exit when the lines ended...My question is why am i not able to read any of the lines...i have about 3-4 lines to read in the txt file and it is not reading any and giving exception at the first line read itself...

Upvotes: 0

Views: 1373

Answers (3)

Achintya Jha
Achintya Jha

Reputation: 12843

if (tmp != null && tmp.equals(""))

should be (if you are trying to check given string is not empty string)

if (tmp != null && !tmp.isEmpty())

I think you reach at the end of file where there is no remaining line and your condition is while(true) so it tries to read that time also . So you getting NoSuchElementException(if no line was found )

So better to change your while loop as

while (s.hasNextLine()){  
   tmp = s.nextLine();
   // then do something

}

Upvotes: 1

PermGenError
PermGenError

Reputation: 46408

I think the better way to code is to have a condition in your while loop using Scanner#hasNextLine(). Scanner#hasNextLine() would make sure that code inside while would only run if it has a line in the file=.

              while (s.hasNextLine()) {
                tmp = s.nextLine();
                if (tmp != null && tmp.equals("")) {
                    result += Integer.parseInt(tmp);
                }

Upvotes: 2

Ilya
Ilya

Reputation: 29693

while (s.hasNextLine())  
{  
   //...  
}

Upvotes: 1

Related Questions