[英]Java array not storing data given to it on initialization
我是Java的新手,正在嘗試使用NetBeans測試小型測驗應用程序。
我將JRadioButtons和按鈕組用於多項選擇題,並且考慮使用數組存儲所有正確答案,如下所示。
private final javax.swing.JRadioButton correctAnswers[]=
{radioButtonOption1Question1,radioButtonOption1Question2,
radioButtonOption1Question3,radioButtonOption1Question4,
radioButtonOption1Question5,radioButtonOption1Question6};
* Edit ,此數組在Netbeans用來初始化我擁有的所有JFrame對象(如單選按鈕)的代碼塊下
但是,每當我在數組上調用時,都會得到一個null指針異常錯誤,並且在進一步調查后發現,該數組僅存儲6個null值。
為什么是這樣? 謝謝
這也是我運行時發送錯誤的循環
for(int i= 0;i<= 5;i++){
if(correctAnswers[i].isSelected()){
numCorrect++;
}
correctAnswers[i].setForeground(Color.green);
}
您可能沒有在任何地方初始化單選按鈕。 請記住,如果要將它們存儲為最終變量,則必須立即執行以下操作:
private final radioButtonOption1Question1 = new JRadioButton( [your options here] )
或類的構造函數中。
您所做的等同於...
JRadioButton radioButtonOption1Question1;
Java可以識別它,但是找不到它的初始化,因此您必須分別初始化每個RadioButton的每個對象。
radioButtonOption1Question1 = new JRadioButton(args[]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.