gpt4 book ai didi

java - 逐行读取文件 - 到达最后一行后终止 while 循环

转载 作者:行者123 更新时间:2023-12-01 11:52:21 25 4
gpt4 key购买 nike

读取文件并打印所有字母字符的程序,当到达最后一行时抛出 NullPointerException。

import java.io.*;

public class Foo {

public static void main(String[] args) throws IOException {

FileReader file = new FileReader(new File("source.txt"));

BufferedReader read = new BufferedReader(file);

String line = read.readLine();

while (line != null) {
for (int i = 0; i < line.length(); i++) {
line = read.readLine(); // this is where the problem is. When it reaches the last line, line = null and the while loop should terminate!
if (Character.isLetter(line.charAt(i))) {
System.out.print(line.charAt(i));
}
}
}
}

}

最佳答案

While 循环不像您在评论中解释的那样工作:

// this is where the problem is. When it reaches the last line, line = null and the while loop should terminate!

While 循环仅检查每次迭代开始时的条件。它们不会仅仅因为下一次迭代开始时条件为假而终止中循环。

因此,您在 while (line != null) 开始时进行的空检查只会且始终在每次迭代的开始时发生,即使 line 在迭代中设置为 null

正如其他人所表明的,您可以将 while 循环构造为:

String line = null;

while ((line = read.readLine()) != null)
{
for (int i = 0; i < line.length(); i++)
{
if (Character.isLetter(line.charAt(i)))
{
System.out.print(line.charAt(i));
}
}
}

并从代码中删除所有其他read.readLine()语句。 (这是最短的代码行)。

或者,如果您想更明确地提高可读性,您可以保留初始的 read.readLine() ,但移动迭代的 read.readLine() 完成所有对 line 的使用后:

String line = read.readLine();

while (line != null)
{
for (int i = 0; i < line.length(); i++)
{
if (Character.isLetter(line.charAt(i)))
{
System.out.print(line.charAt(i));
}
}
line = read.readLine();
//line is never used after this so an NPE is not possible
}

关于java - 逐行读取文件 - 到达最后一行后终止 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28705491/

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