简体   繁体   English

Java数组不存储初始化时提供给它的数据

[英]Java array not storing data given to it on initialization

I'm a newb to Java and am trying to test a small quiz app with NetBeans. 我是Java的新手,正在尝试使用NetBeans测试小型测验应用程序。

I'm using JRadioButtons and button groups for multiple choice questions, and I thought to use an array to store all of the correct answers, as seen below. 我将JRadioButtons和按钮组用于多项选择题,并且考虑使用数组存储所有正确答案,如下所示。

private final javax.swing.JRadioButton correctAnswers[]= 
    {radioButtonOption1Question1,radioButtonOption1Question2,
    radioButtonOption1Question3,radioButtonOption1Question4,
    radioButtonOption1Question5,radioButtonOption1Question6};

*Edit , this array is under the block of code Netbeans makes to initizialize all of the JFrame objects I have like the radiobuttons * Edit ,此数组在Netbeans用来初始化我拥有的所有JFrame对象(如单选按钮)的代码块下

However whenever I call on the array I get a null pointer exception error, and upon further investigation I found that the array was only storing 6 null values. 但是,每当我在数组上调用时,都会得到一个null指针异常错误,并且在进一步调查后发现,该数组仅存储6个null值。

Why is this? 为什么是这样? Thanks 谢谢

Also here's the loop sending the error when I run it 这也是我运行时发送错误的循环

for(int i= 0;i<= 5;i++){
    if(correctAnswers[i].isSelected()){
    numCorrect++;
    }

    correctAnswers[i].setForeground(Color.green);
}

You are probably not initializing your radiobuttons anywhere. 您可能没有在任何地方初始化单选按钮。 Keep in mind that if you want to store them as final variables, you HAVE to do it immediately: 请记住,如果要将它们存储为最终变量,则必须立即执行以下操作:

private final radioButtonOption1Question1 = new JRadioButton( [your options here] )

or in the constructor of your class. 或类的构造函数中。

What you have done is the equivalent of... 您所做的等同于...

JRadioButton radioButtonOption1Question1;

Java recognizes it but cant find it's initialization so you've got to initialize everyone of those RadioButtons individually. Java可以识别它,但是找不到它的初始化,因此您必须分别初始化每个RadioButton的每个对象。

radioButtonOption1Question1 = new JRadioButton(args[]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM