gpt4 book ai didi

Java - 字符串数组上的空指针异常

转载 作者:行者123 更新时间:2023-12-02 05:01:28 24 4
gpt4 key购买 nike

这是我正在处理的代码。它位于一个方法内部,其想法是打开一个文件并检查内容或缺少内容,然后进行报告。

但是,我在下面指向的行上遇到了 NullPointerException

我不知道如何解决这个问题。我尝试调试,结果表明在运行该行时,String[] 的第一个元素包含文本,因此这不是问题。

int i = 0;
int numChar=1, numLines;
String[] line = new String[1000];

try {
BufferedReader in = new BufferedReader(new FileReader(file));
try {
while(numChar > 0) {
//String[] line = new String[1000];
line[i] = in.readLine();
PROBLEM--> numChar = line[1].length();
i++;
}
} catch (EOFException ex) {
JOptionPane.showMessageDialog( null, "Error" );
//break;
}
}
catch(IOException e) {
JOptionPane.showMessageDialog( null, "Missing file or no data to read." );
System.out.println("IO Error - Missing file");
}

最佳答案

我怀疑您只需更改数组访问索引以使用 i 而不是 1

numChar = line[i].length();

您还应该检查 null,因为 BufferedReader 将返回 ( from the docs ):

null if the end of the stream has been reached

numChar = line[i] == null ? 0 : line[i].length;

您可能想要扩展它,以便跳出循环,而不是分配 null 长度。

String s = in.readLine();
if (s == null) {
break;
}
else {
line[i] = s;
numChar = line[i++].length();
}

编辑以回应评论。

冒着混淆问题的风险,我的首选是重写你的循环。您似乎不需要循环外部的 numChars ,因此我将删除它以减少方法范围的变量。我还怀疑您不想在流末尾停止阅读空行:

while (true) { // for(;;) if you prefer
String s = in.readLine();
//if (s == null || s.length() == 0) break; // stop on empty lines and end of stream
if (s == null) break; // stop at end of stream only
line[i++] = s;
}

关于Java - 字符串数组上的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28252589/

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