This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


5年前关闭。




我的代码可以编译,但是在运行时出现此错误:

Exception in thread "main" java.lang.ExceptionInInitializerError
    at GUI.<init>(GUI.java:46)
    at GUI.main(GUI.java:252)
Caused by: java.lang.NullPointerException
    at java.util.Objects.requireNonNull(Objects.java:203)
    at java.util.Arrays$ArrayList.<init>(Arrays.java:3813)
    at java.util.Arrays.asList(Arrays.java:3800)
    at db.<clinit>(db.java:23)
    ... 2 more


这是导致错误的代码:

public static String strLine;
public static String[] filearray;
public static List<String> list = Arrays.asList(filearray);


public static void load() throws IOException{

FileInputStream in = new FileInputStream("slist.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));

filearray = new String[4];

while ((strLine = br.readLine()) != null) {

for (int j = 0; j < filearray.length; j++){
filearray[j] = br.readLine();

}

}
in.close();


错误中引用的第46行:

JList stafflist = new JList(db.list.toArray());


我正在尝试将文本文件加载为Array并将其添加到JList人员列表,但是出现运行时错误。

最佳答案

在您的声明中:

public static String[] filearray;
public static List<String> list = Arrays.asList(filearray);


fileArray为空,您正在尝试围绕它创建一个列表。

您可以在此处初始化fileArray

public static String[] filearray = new String[4];


或将值放入Arrays.asList(filearray)后调用filearray

07-27 18:00