user1781453
user1781453

Reputation: 25

scan.hasNext() breaks before printing last line in code in While loop?

Why is this loop not printing the last line in the .txt file that I have saved elsewhere? It prints out all the lines except the very last one.

int count = 0;

Courses[] POS = new Courses[26];

while (scan.hasNext())
{
    POS[count] = new Courses(scan.nextLine());

    System.out.println(POS[count]);
    scan.nextLine();

    count++;
}

Upvotes: 0

Views: 291

Answers (2)

Brenden Brown
Brenden Brown

Reputation: 3215

I think the problem is that, as demongolem pointed out in the comments, you're calling scan.nextLine() twice.

If you have an even-numbered length of lines, that would mean this would print out every other line. If you have an odd-numbered length of lines, that would mean it would print out every other line, then throw an exception (NoSuchElement I believe?)

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextLine.

Upvotes: 0

Caesar Ralf
Caesar Ralf

Reputation: 2233

You are getting the next line twice. You are lucky it doesn't throw a NPE or another exception :P

Upvotes: 1

Related Questions