I'm writing a simple program in Java and it requires reading data from a text file. However, I'm having trouble counting lines. The issue seems generic enough for a simple Google search but I may not even be searching the right things.
The textbook I'm learning from suggests that to count the number of lines in a text file, you should do something like this:
public static int[] sampleDataArray(String inputFile) throws IOException
{
File file = new File(inputFile);
Scanner inFile = new Scanner(file);
int count = 0;
while (inFile.hasNext())
count++;
int[] numbersArray = new int[count];
inFile.reset();
for (int i = 0; i < count; i++)
{
numbersArray[i] = inFile.nextInt();
}
inFile.close();
return numbersArray;
}
It seems to me that the while (inFile.hasNext())
line is the problem. I think the hasNext()
is running infinitely. The data file that I'm using with the code definitely has a finite number of lines of data.
What should I do?
You can not use the scanner to count the no of line in file because as default scanner uses white space to separate tokens. I would suggest to use BufferReader and readline method.
http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html
For counting number of lines use
hasNextLine()
, instead ofhasNext()
.In
while
loop you are supposed to callnextLine()
, because in your current implementation scanner is static on first line. Calling this method will make it to move to the next line, in every iteration of loop.Refer to the following code snippet:
After you call
hasNext()
the first time if you don't read from the filehasNext()
will always return true. Because the front of the input doesn't change.Imagine you have a file with this line in it:
If you call
hasNext()
on this file, it will returntrue
because there is a next token in the file, in this case the wordthis
.If you don't read from the file after this initial call, the "next" input to be processed is STILL the word
this
. The next input doesn't change until you read from the file.TL;DR
When you call
hasNext()
read from the file, otherwise you will always have an infinite loop.Additionally
If you really want to use
hasNext()
, or would like to, you could create anotherScanner
object and read through the file to count the lines, then your loop would work fine. also, you should really usehasNextLine()
Hope this is helpful.
inFile.hasNext()
does not move the pointer to the next linetry this
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#hasNext%28%29