我是java新手,在处理对象数组时遇到了问题。我的主程序是这样的:
package bicycledemo;
class BicycleDemo {
public static void main(String[] args) {
// Create two different
// Bicycle objects with an array
Bicycle[] bike = new Bicycle[2];
bike[0].cadence=50; //line 10, where the NullPointerException prompts out
bike[0].gear=2;
bike[1].cadence=10;
bike[1].gear=3;
System.out.println("gear: "+bike[0].gear+"\n"+"cadence: "+bike[0].cadence+"\n");
System.out.println("gear: "+bike[1].gear+"\n"+"cadence: "+bike[1].cadence+"\n");
System.out.println("\b");
}
}
自行车类是这样的:
package bicycledemo;
public class Bicycle {
public Bicycle() {
}
public int cadence;
public int gear;
}
当我运行程序时,输出错误是:
Exception in thread "main" java.lang.NullPointerException
at bicycledemo.BicycleDemo.main(BicycleDemo.java:10)
Java Result: 1
我想发生的事情是没有正确创建对象自行车,但我不明白为什么。
非常感谢您的帮助!我真的很想解决这个问题!