java Scanner 类 hasNextLine 无限循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7974238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:17:11  来源:igfitidea点击:

Scanner Class hasNextLine infinite loop

javafileloopsinput

提问by KWJ2104

why does this piece of code go into 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 print line just keeps going.

打印线一直在运行。

回答by b.buchhold

Because hasNexLine()does neither get the line nor change the state of the scanner. if it's true once, and no other methods of the scanner are called, it'll always be true.

因为hasNexLine()既不会得到线路也不会改变扫描仪的状态。如果它一次为真,并且没有调用扫描仪的其他方法,则它将始终为真。

回答by OscarRyz

Because you have to consume the nextLine so the code should be:

因为你必须使用 nextLine 所以代码应该是:

while ( theScanner.hasNextLine() ) {
    String theLine = theScanner.nextLine();
}

If you don't invoke nextLine()you will always be watching at the same line and it will always answer true to that.

如果您不调用,nextLine()您将始终在同一行观看,并且它始终会对此做出正确的回答。

回答by AusCBloke

Add a call to nextLineor any other Scannermethod that'll read in some input inside the whileloop.

添加对循环内某些输入的调用nextLine或任何其他Scanner方法while

At the moment you're just repeatedly calling hasNextLine(which onlyreturns a boolean, it doesn't modify the stream) without retrieving any input from freader, so if freaderinitially has another line within its input hasNextLinewill alwaysreturn true and your loop is essentially while (true).

此刻你只是重复调用hasNextLine(其中返回一个boolean未经任何检索输入,它不会改变流)freader,因此,如果freader最初有其内输入另一行hasNextLine始终返回true,你的循环本质while (true)