gpt4 book ai didi

java - 被诅咒的 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-01 07:05:51 25 4
gpt4 key购买 nike

我的应用程序旨在将包含 1500 个项目的现有文本文件逐行读取到项目类对象数组中。目标是将数据放入数组中,以便我可以使用此应用程序作为转换我正在编写的新程序的存档的起点。

package sandboxPackage;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class mainClass {
public static void main(String[]args) throws FileNotFoundException, IOException {
InputStream in = new FileInputStream(new File("C:\\Documents and Settings\\Adam\\Desktop\\Cloud Project\\MasterIndex.library"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
itemClass[] m = new itemClass[1500];
int i = 0;
while ((line = reader.readLine()) != null) {
m[i].index = line; // crash is here
m[i].location = reader.readLine();
m[i].item = reader.readLine();
m[i].description = reader.readLine();
i++;
}

//Print the entire list
for (i = 0; i == 1499; i++) {
System.out.println(m[i].index);
System.out.println(m[i].location);
System.out.println(m[i].item);
System.out.println(m[i].description);
//System.out.println("This is item #" + i + 1);
}

}
}

这是 itemClass:

package sandboxPackage;
public class itemClass{
String index;
String item;
String description;
String location;
}

文本文件如下所示:指数地点元素描述指数地点元素描述指数..

编译器声称 NullPointerException 位于第 20 行,即 while 循环的第一行,但我只是没有看到它。我已经查看了大约一千个相同错误的其他示例,但它仍然无法为我计算。

最佳答案

您只是声明一个对象数组:

itemClass[] m = new itemClass[1500];

但您从未实例化此数组中的对象。因此访问任何实例变量都会抛出 NullPointerException

在循环中添加数组对象的实例化:

while ((line = reader.readLine()) != null) {
m[i] = new itemClass();// change the constructor if u need to
m[i].index = line; // crash is here : should no more crash
m[i].location = reader.readLine();
m[i].item = reader.readLine();
m[i].description = reader.readLine();
i++;
}

关于java - 被诅咒的 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791657/

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