【发布时间】:2021-07-02 18:50:15
【问题描述】:
我有一个ParkingLot 类,它有一个getEmptySpaces() 方法,适用于ParkingLot 对象,它们是Car 对象的数组。
我想调用lot.getEmptySpaces(),但是如果我给它一个数组而不是一个特定的项目,我的IDE Netbeans 就会出错。 lot[1].getEmptySpaces() 编译得很好,但运行时崩溃,正如预期的那样,因为它应该接收一个数组,而不是 null。
如何在同一个类定义的数组上调用方法?
// Main
ParkingLot[] lot = new ParkingLot[10];
lot[1].getEmptySpaces(); // compiles but doesn't run
lot.getEmptySpaces(); // what i want to run but doesn't
// Car class
public class Car {
private String color;
private String licensePlate; // lp #
public Car(String color, String licensePlate) {
this.color = color;
this.licensePlate = licensePlate;
}
/**
* @return the color
*/
public String getColor() {
return color;
}
/**
* @param color the color to set
*/
public void setColor(String color) {
this.color = color;
}
/**
* @return the licensePlate
*/
public String getLicensePlate() {
return licensePlate;
}
/**
* @param licensePlate the licensePlate to set
*/
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
@Override
public String toString() {
return "Car{" + "color=" + color + ", licensePlate=" + licensePlate + '}';
}
}
// ParkingLot class
public class ParkingLot {
private Car[] spaces; // lp=000000 color=none will represent an empty space
private int currentIndex;
/**
* Creates a parkingLot object
*
* @param size how many spaces are needed in the parking lot
*/
public ParkingLot(int size) {
// Array Example: String[] arr = new String[20];
this.spaces = new Car[size];
this.currentIndex = 0;
}
public int getEmptySpaces(){
int emptySpaces = 0;
for(int i = 0; i < spaces.length; i++){
if (spaces[i] == null){
emptySpaces++;
}
}
return emptySpaces;
}
/**
* Adds a car to the parking lot
*
* @param car the car to be added to the parking lot
*/
public void addCar(Car car){
spaces[currentIndex] = car;
currentIndex++;
}
}
【问题讨论】:
-
您是要定义一个有 10 个车位的停车场,还是定义一个包含 10 个停车场的数组?因为如果您尝试定义单个停车场,则需要使用以下语法:
ParkingLot lot = new ParkingLot(10);——请注意调用的类型/括号中缺少方括号。如果你试图定义一个停车场数组,你需要一个循环来初始化它们,然后你需要在单个索引处访问数组来进行调用,或者使用某种 map / foreach 语法。跨度> -
当然
lot.getEmptySpaces()不会工作,因为lot是一个数组(ParkingLots)。而数组,无论是ParkingLots 还是其他的,都没有`getEmptySpaces()` 方法。如果您的目标是找出所有停车场的空车位总数,则需要循环遍历数组,并在每个ParkingLot上调用getEmptySpaces(),然后自己将它们相加。 -
停车场不应该包含一系列汽车,而应该包含一个 Spaces 数组,每个 Spaces 都可以包含一辆汽车。
-
如果你总是在数组末尾添加一辆汽车,计算空格你需要做的就是返回
spaces.length-currentIndex。例如,当数组为空时,数组长度为10,当前索引为零;为您提供 10 个可用空间 (10 - 0)。同样,当最后一辆车被添加到数组中时,这辆车被添加到第 9 个索引并且索引增加到 10,给你零个可用空间 (10 - 10)。无需遍历数组即可计算。