我正在用Java开发一个停车场项目,当我运行我的程序时,我收到以下错误消息:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "ParkingSpace.getSpaceNum()" because "pl.parkingLot[5]" is null at ParkingLot.main(ParkingLot.java:67)
我不明白为什么
pl.parkingLot[5]
是null
,因为我以为我已经用for循环在数组parkingLot的每个索引处初始化了ParkingSpace
。
我认为当我在 ParkingLot 的类构造函数中使用 for 循环为数组
parkingLot
赋值时,调用 parkingLot[5]
不会导致 null
。
另外,我希望该程序运行并在控制台的一行上打印 5,并在下一行打印 4,但运行该程序会导致 NullPointerException。
这是我的 ParkingLot 类的代码:
public class ParkingLot {
ParkingSpace[] parkingLot;
int numSpaces;
int numFloors;
ParkingLot(int numSpaces, int numFloors){
this.numSpaces = numSpaces;
this.numFloors = numFloors;
ParkingSpace[] array = new ParkingSpace[numSpaces];
parkingLot = new ParkingSpace[numSpaces];
char currentFloor = 'A';
for(int i = 0; i < numFloors; i++){
for(int j = 0; j < numSpaces; j++){
parkingLot[j] = new ParkingSpace(j, currentFloor, false);
if(j<4){
parkingLot[j].isCompact = true;
}
j++;
}
currentFloor++;
i++;
}
}
ParkingSpace enterLot(boolean com){
ParkingSpace returnValue = new ParkingSpace(0,'A', false);
for(int i = 0; i < numFloors; i++) {
for (int j = 0; j < numSpaces; j++) {
if (!parkingLot[j].isOccupied) {
if (com) {
returnValue = parkingLot[j];
} else if (i > 3) {
returnValue = parkingLot[j];
} else {
j++;
}
} else {
j++;
}
}
i++;
}
return returnValue;
}
void leaveLot(ParkingSpace space){
for(int i = 0; i < numFloors; i++){
if(i == space.floor){
for(int j = 0; j < numSpaces; j++){
if(j == space.spaceNum){
space.isOccupied = false;
}else{
j++;
}
}
}else{
i++;
}
}
}
public static void main(String[] args){
ParkingLot pl = new ParkingLot(6, 6);
System.out.println(pl.parkingLot[5].getSpaceNum());
System.out.println(pl.enterLot(false));
}
}
这是 ParkingSpace 类:
public class ParkingSpace {
int spaceNum;
char floor;
boolean isCompact;
boolean isOccupied;
ParkingSpace(int spaceNum, char floor, boolean isCompact){
this.spaceNum = spaceNum;
this.floor = floor;
this.isCompact = isCompact;
isOccupied = false;
}
int getSpaceNum(){
return spaceNum;
}
char getFloor(){
return floor;
}
boolean getCompact(){
return isCompact;
}
boolean getOccupied(){
return isOccupied;
}
void setOccupied(boolean value){
isOccupied = value;
}
String toAString(){
char compact;
char occupied;
if(isCompact){
compact = 'C';
}else{
compact = 'N';
}
if(isOccupied){
occupied = 'X';
}else{
occupied = 'O';
}
return(floor + spaceNum + " (" + compact + " " + occupied + ")");
}
为什么要在循环体中增加i和j?您初始化每个第二层和空间。