KWJ*_*104 3 java loops file input
当我尝试给它一个基本的文本文件时,为什么这段代码进入无限循环?
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();
}
}
Run Code Online (Sandbox Code Playgroud)
印刷线一直在继续.
因为你必须使用nextLine所以代码应该是:
while ( theScanner.hasNextLine() ) {
String theLine = theScanner.nextLine();
}
Run Code Online (Sandbox Code Playgroud)
如果你不调用,nextLine()你将始终在同一条线上观看,它总是会回答这一点.