[英]My Java code crashes when I try to call a method from an array of objects
I'm just learning Java and trying to have an array of a class.我只是在学习 Java 并试图拥有一个 class 的数组。 When a call a methed from the array it crashes.当从数组中调用一个方法时,它会崩溃。 Works fine if it is not an array如果它不是数组,则可以正常工作
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cDate test=new cDate();
test.setDay(0);
mAppoitments = new cDate[24];
// crashes why?????
mAppoitments[0].setDay(0);
You haven't filled your array with objects.你还没有用对象填充你的数组。 You have to:你必须:
cDate[0] = test;
Otherwise you have null
at index 0, and you cannot invoke anything on null
.否则,您在索引 0 处有null
,并且您不能在null
上调用任何内容。
And next time you ask a question, give all needed details:下次您提出问题时,请提供所有需要的详细信息:
You have an array of 24 objects, each of which is set to null
.您有一个包含 24 个对象的数组,每个对象都设置为null
。 You need to initialize each one before you can call methods on it.您需要先初始化每一个,然后才能对其调用方法。
You have initialized the array but not the objects in the array.您已初始化数组,但未初始化数组中的对象。 Try initializing these elements before using them.在使用它们之前尝试初始化这些元素。
mAppoitments = new cDate[24];
for (int i = 0; i < mAppoitments.length; i++)
mAppoitments[i] = new cDate();
mAppoitments[0].setDay(0);
final int COUNT= 24;
mAppoitments = new cDate[COUNT];
for(int i = 0 ; i < COUNT ; ++i) {
mAppoitments[i] = new cDate();
mAppoitments[i].setDay(0);
}
cDate myAppointments = new cDate[24];
try declaring the variable type尝试声明变量类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.