在Java中使用数组对象从其他类调用方法
为什么这个代码不起作用?似乎我无法使用数组将变量设置为“10”,但对于普通对象它可以工作 我做错了什么 一级在Java中使用数组对象从其他类调用方法,java,Java,为什么这个代码不起作用?似乎我无法使用数组将变量设置为“10”,但对于普通对象它可以工作 我做错了什么 一级 public class apples { public static void main(String[] args) { carrots carrotObj = new carrots(); carrotObj.setVar(5); System.out.println(carrotObj.getVa
public class apples {
public static void main(String[] args) {
carrots carrotObj = new carrots();
carrotObj.setVar(5);
System.out.println(carrotObj.getVar());
carrots carrotArray[] = new carrots[3];
carrotArray[1].setVar(10);
System.out.println(carrotArray[1].getVar());
}
}
二级
public class carrots {
private int var = 0;
public int getVar() {
return var;
}
public void setVar(int var) {
this.var = var;
}
}
控制台输出:
5
Exception in thread "main"
java.lang.NullPointerException
at apples.main(apples.java:17)
您创建了一个数组,但是当创建一个对象数组时,它们都被初始化为
null
——对象引用变量的默认值。您需要创建一些对象并将它们指定给阵列中的插槽
carrots carrotArray[] = new carrots[3];
// Place this code
carrotArray[1] = new carrots();
carrotArray[1].setVar(10);
您可以对位置0和2执行类似的操作
此外,Java约定是将类名大写,例如,
Carrots
您需要初始化数组的所有元素;因为它们不是空的,所以它们的默认值是null
carrots carrotArray[] = new carrots[3];
for(int i=0; i < carrotArray.length; i++){
carrotArray[i] = new carrots();
}
carrotArray[1].setVar(10);
System.out.println(carrotArray[1].getVar());
carrots-carrotary[]=新胡萝卜[3];
for(int i=0;i
您需要自己用对象填充数组。这里有一个NPE:carrotary[1]
另外,类的首字母大写,即Apples和Carrotscarrotary[1]=new Carrots()
beforearrotary[1].setVar(10)代码>。感谢你们两位的回复!谢谢你的帮助!谢谢你的帮助!