Java – scanner class hasnextline infinite loop

Why does this code enter an infinite loop when I try to give it a basic text file?

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class TestFile
{

    public static void main(String args[]) throws IOException
    {
            // Read in input file                                                                                                                                            
            File input = new File(args[0]);
            Scanner freader = new Scanner(input);
            while (freader.hasNextLine()) {
                System.out.println("hi");
            }

            freader.close();

    }

}

The printing line continues

Solution

Because hasnexline() neither gets lines nor changes the state of the scanner If it is true once and no other method of scanner is called, it will always be true

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>