Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

java - Scanner on text file hasNext() is infinite

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After you call hasNext() the first time if you don't read from the file hasNext() will always return true. Because the front of the input doesn't change.

Imagine you have a file with this line in it:

this is input

If you call hasNext() on this file, it will return true because there is a next token in the file, in this case the word this.

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 another Scanner object and read through the file to count the lines, then your loop would work fine. also, you should really use hasNextLine()

public int countLines(File inFile)
{
   int count = 0;
   Scanner fileScanner = new Scanner(inFile);

   while(fileScanner.hasNextLine()) //if you are trying to count lines
   {                                //you should use hasNextLine()
       fileScanner.nextLine() //advance the inputstream
       count++;
   }

   return count;
}

Hope this is helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...