WordSide
WordSide

Reputation: 11

Why does the counter keep counting when i'm using .hasNext in file io in java

Basically, I'm trying to count how many lines in a txt file and then store it to an array as index.

File file = new java.io.File("number.txt");
Scanner s = new Scanner(file);
int count = 0;
while(s.hasNextLine())
{     
    count++;
    System.out.println(count);
}
System.out.println("There is: " + count + " line );
int[] array = new int[count];

However, I realize that the "count" go infinity and it never stop counting, but I only have 20 line in my txt file. Why is this happening??

Note: I know how to fix , but i just curious about why it keep counting

Upvotes: 0

Views: 382

Answers (2)

ndlu
ndlu

Reputation: 161

Because that is the way it is designed.

public boolean hasNextLine()

Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.

Returns: true if and only if this scanner has another line of input Blockquote

Throws: IllegalStateException - if this scanner is closed

Upvotes: 0

Jinal Shah
Jinal Shah

Reputation: 315

You should be using

scanner.nextLine()

in conjunction with

scanner.hasNextLine()

hasNextLine will check if the there is next line available or not but it will not goto the next line for that you need to use nextLine. When both of them are used you will see the counter stop after it has parsed the last line. So your code should be something like this

File file = new java.io.File("number.txt");
Scanner s = new Scanner(file);
int count = 0;
while(s.hasNextLine())
{   
    s.nextLine();
    count++;
    System.out.println(count);
}
System.out.println("There is: " + count + " line );
int[] array = new int[count];

Upvotes: 4

Related Questions