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?
int[]
byList<Integer>
. This way you don't need to know the size beforehand and it saves you from one more loop. – Dusky