我使用 BufferedReader 为从文本文件读取的方法编写了一个 do-while 代码。如果你想要上下文,我正在做一个臭名昭著的基于文本的冒险游戏,这个方法是从文本文件中提取我的游戏“项目”,这样它们就可以制作成我的 HashMap 中的对象。
无论如何,我的一些描述有多行,所以我想确保它能够捕获每一行。
这是完整的代码块:
while ((currentLine = readerObject.readLine()) != null) {
if (currentLine.startsWith("name: ")) {
name = currentLine.substring(6);
} else if (currentLine.startsWith("location: ")) {
location = currentLine.substring(10);
} else if (!currentLine.startsWith("DONE")) {
do {
if (currentLine.startsWith("description: ")) {
description = currentLine.substring(13);
currentLine = readerObject.readLine();
} else {
description = description.concat(currentLine);
currentLine = readerObject.readLine();
}
} while (!currentLine.startsWith("DONE"));
itemsAll.put(name, new Items(name, location, description));
}
}
这是我的代码中存在问题的特定部分:
do {
if (currentLine.startsWith("description: ")) {
description = currentLine.substring(13);
currentLine = readerObject.readLine();
} else {
description = description.concat(currentLine);
currentLine = readerObject.readLine();
}
} while (!currentLine.startsWith("DONE"));
如果以“description:”开头的行后面紧跟着“DONE”行,那么我的目的是在第一次迭代结束时评估退出条件时退出循环。相反,它循环回另一个迭代,因此当它到达退出条件时,它认为 currentLine 为空,并给我这个:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.startsWith(String)" because "<local2>" is nullat TextInput.inputItems(TextInput.java:64)
我很困惑为什么在 currentLine 更新为 DONE 后 do-while 循环不退出?我已经在纸上手动完成了它(确定每个步骤的每个值和输出),并添加到打印语句中以测试问题所在,但我只是不明白为什么。
我已经找到了一个更精简的解决方案,但我觉得我错过了一些关于为什么原始代码不起作用的基本信息......任何人都可以解释吗?
抱歉,如果原因很明显......我今天编码了太多时间,所以我的大脑可能很糊涂。
我发现有两件事可能出了问题:
虽然内部
do/while
结束了,但最上面的while循环仍在执行。所以,这就是你的程序没有退出的原因。
您需要以与最顶层
do/while
循环中相同的方式在 while
内进行空检查。具体来说,在您这样做之后:currentLine = readerObject.readLine();