我正在尝试打印Car数组中的所有元素。但是控制台显示它存在空指针问题。
假设我有一个名为Car的类,并且Car类中没有错。 CarLeadership类可操纵Car对象组。我将它们放在名为carArr(CarLeadership类中的一个属性)的数组中。
public class CarLeadership {
private Car[] carArr;
private int position; //point to the current element of carDatabase
//pass length of array
public CarLeadership(int maxCar) {
Car[] carArr = new Car[maxCar];
position=0;
}
//parameterized constructor
public CarLeadership(Car[] carDatabase,int position) {
carArr = carDatabase;
this.position = position;
}
//copy constructor
public CarLeadership(CarLeadership c) {
this.carArr = c.getCarArr();
this.position = c.position;
}
public void setCarArr(Car[] carArr) {
this.carArr = carArr;
}
public void setCarArrElements(int index,Car carObj) {
if(index >= carArr.length) {
System.out.println("Index out of bounds");
System.exit(0);
}
carArr[index] = carObj;
}
public Car[] getCarArr() {
//deep copy
Car[] anotherCarArr = new Car[this.carArr.length];
for(int i=0; i<anotherCarArr.length;i++)
anotherCarArr[i] = this.carArr[i];
return anotherCarArr;
}
public void setPosition(int position) {
this.position = position;
}
public int getPosition() {
return position;
}
public String toString() { //instance has carArr
String s="";
for(int i=0;i<carArr.length;i++)
if(carArr[i]!= null)
s += ("Car: # "+ i + "\nMake: " +this.carArr[i].getMake()
+"\nModel: "+this.carArr[i].getModel()
+"\nYear: "+this.carArr[i].getYear()
+"\nPrice: "+this.carArr[i].getPrice()+"\n");
return s;
}
}
//driver class
public class CarLeadershipDriver {
public static void main(String[] args) {
// TODO Auto-generated method stub
CarLeadership cc = new CarLeadership(5);
cc.setCarArrElements(0,new Car("aa","cc",2018,242));
cc.setCarArrElements(1,new Car("aa","aa",2018,242));
cc.setCarArrElements(2,new Car("aa","cc",2018,242));
System.out.println(cc);
}
}
错误消息:
Exception in thread "main" java.lang.NullPointerException
at CarLeadership.setCarArrElements(CarLeadership.java:31)
at CarLeadershipDriver.main(CarLeadershipDriver.java:7)
答案 0 :(得分:1)
更改构造函数
public CarLeadership(int maxCar) {
Car[] carArr = new Car[maxCar];
position = 0;
}
到
public CarLeadership(int maxCar) {
carArr = new Car[maxCar];
position = 0;
}
仅此而已。
现在您的程序以输出运行:
Car: # 0
Make: aa
Model: cc
Year: 2018
Price: 242
Car: # 1
Make: aa
Model: aa
Year: 2018
Price: 242
Car: # 2
Make: aa
Model: cc
Year: 2018
Price: 242
答案 1 :(得分:1)
问题在于您正在构造函数中初始化carArr的本地副本。
替换
//pass length of array
public CarLeadership(int maxCar) {
Car[] carArr = new Car[maxCar];
position=0;
}
与
//pass length of array
public CarLeadership(int maxCar) {
carArr = new Car[maxCar];
position=0;
}
或者如果您想更明确
//pass length of array
public CarLeadership(int maxCar) {
this.carArr = new Car[maxCar];
position=0;
}
答案 2 :(得分:0)
您在构造函数中创建了新数组,同时应将声明的大小分配给现有数组。
this.carArr =新车[maxCar];