gpt4 book ai didi

java - 我的程序陷入从文件读取的 while 循环中

转载 作者:行者123 更新时间:2023-12-01 20:52:39 24 4
gpt4 key购买 nike

public static void main(String[] args) throws IOException{
//System.out.print("ok");
Scanner fileReader = new Scanner(new File("EmployeeInfo.txt"));
//System.out.print(fileReader.nextInt());

while(fileReader.hasNext()){
System.out.print("ok");
int year = 2014;
//int year = fileReader.nextInt();
if(year == 2014){

System.out.print("ok");

}//end if


}// end while loop



}//end main method

我不确定为什么它卡在 while 循环中。我已经验证该程序打开该文件并且可以读取它。

最佳答案

那是因为您没有在 while 循环中调用 nextLine() (或 nextXXX())方法,这意味着 扫描仪永远不会前进到下一个标记。

这就是documentation nextLine() 方法说:

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

因此,您需要在 while 循环内调用 nextLine() 来迭代各行并到达文件末尾,以便控制从中出来。

关于java - 我的程序陷入从文件读取的 while 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42964268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com