gpt4 book ai didi

java - 填充二维数组时出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 10:58:39 24 4
gpt4 key购买 nike

我正在小程序中构建一个小游戏。每当我尝试运行它时,都会出现以下错误 buttons[i][k] = new ActiveSquare(k);

错误:

java.lang.NullPointerException
at com.proj3.renee.ClickAid.<init>(ClickAid.java:21)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at java.lang.Class.newInstance(Class.java:379)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:795)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:724)
at sun.applet.AppletPanel.run(AppletPanel.java:380)
at java.lang.Thread.run(Thread.java:745)

我已经阅读了类似的答案和 newInstance0 问题,并且已经检查以确保 ActiveSquare 中的类正常工作,但我仍然无法找到问题所在。任何建议或进一步阅读将不胜感激。这是第一段代码和构造函数(如果需要,我可以发布更多内容):

public class ClickAid extends Applet implements ActionListener {
ActiveSquare[][] buttons;
private static final long serialVersionUID = 1L;

public ClickAid() {
setLayout(new GridLayout(0, 2, 5, 5));
JPanel panel = new JPanel();
add(panel);

for (int i = 0; i < 4; ++i){//default = 4
for (int k = 0; k < 6; ++k){
buttons[i][k] = new ActiveSquare(k); //this is where the error is
panel.add(buttons[i][k].buttonaspect);
buttons[i][k].buttonaspect.addActionListener(this);
}
}
}

最佳答案

您必须初始化数组的 buttons[i] 元素。 buttons[i] = new ActiveSquare[6]

关于java - 填充二维数组时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33465177/

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