【发布时间】:2014-09-15 22:07:20
【问题描述】:
我正在编写代码来读取文本文件并计算文本文件中的所有单词。但是在 while 循环中,字符串数组得到了 NullPointerException。我有点明白这意味着该对象没有被指向或类似的东西,但我不知道如何修复它。
public class W273 {
public static void main(String[] args) throws IOException {
while (JPL.test()) {
String fileName = "phillip.txt";
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = in.readLine();
String[] words = line.split(" ");
int count = 0;
String loop;
while (in != null) {
// move this line
words = line.split(" ");
for (int i = 0; i < words.length; i++) {
loop = words[i]; // NullPointerException here
count++;
}
line = in.readLine();
}
in.close();
System.out.print(count);
}
}
}
【问题讨论】:
-
我敢打赌这不是你的 NPE 发生的地方。
-
我在这里看到一个无限循环...
-
您的意思是
while (line != null)?此外,您可能想查看do { } while (test);结构。您可以消除对line的冗余初始捕获。 -
请发布完整堆栈跟踪。 将其编辑到问题中。
-
@owlstead:这个问题是针对 OP 的,
in在 while 循环中的任何地方都不能为空。
标签: java arrays string nullpointerexception