gpt4 book ai didi

java - 将多个 Java 对象数组传递给另一个方法

转载 作者:行者123 更新时间:2023-12-02 02:06:07 29 4
gpt4 key购买 nike

我刚刚开始学习java,之前有一些Python方面的经验和一点JavaScript,但没有使用类。我对此代码有疑问(仅供引用,下面我指出了确切的问题):

public class Race {
Boolean isThereABrokenTruck = false;
private Car[] cars;
private Motorcycle[] motorcycles;
private Truck[] trucks;
private void createVehicles() {
cars = new Car[10];
motorcycles = new Motorcycle[10];
trucks = new Truck[10];

} // creates 10 cars, 10 trucks and 10 motorcycles.

private void simulateRace() {
Weather.setRaining();
for (Car car : cars) {
for (int i = 0; i < 50; i++) {
car.moveForAnHour();
}
}
for (Motorcycle motorcycle : motorcycles) {
for (int i = 0; i < 50; i++) {
motorcycle.moveForAnHour();
}
}
for (Truck truck : trucks) {
for (int i = 0; i < 50; i++) {
truck.moveForAnHour();
}
}

}
private void printRaceResults() {
for (Car car : cars) {
System.out.println("Name: " + car.name);
System.out.println("\n Distance Travelled: " + car.distanceTraveled);
System.out.println("\n Type:" + car.getClass().getName());
}
for (Motorcycle motorcycle : motorcycles) {
System.out.println("Name: " + motorcycle.name);
System.out.println("\n Distance Travelled: " + motorcycle.distanceTraveled);
System.out.println("\n Type:" + motorcycle.getClass().getName());
}
for (Truck truck : trucks) {
System.out.println("Name: " + truck.name);
System.out.println("\n Distance Travelled: " + truck.distanceTraveled);
System.out.println("\n Type:" + truck.getClass().getName());
}
} // prints each vehicle's name, distance traveled ant type.

protected Boolean isThereABrokenTruck() {
return isThereABrokenTruck;
}

public static void main(String[] args) {
Race race = new Race();
race.createVehicles();
race.simulateRace();
race.printRaceResults();
}
}

这段代码可以编译(汽车、摩托车和卡车类也在我的代码中定义,但与问题无关),但是我在

上得到运行时空指针异常
   for (Car car : cars) { // null pointer exception here
for (int i = 0; i < 50; i++) {
car.moveForAnHour();
}
}

所以我想我没有正确地为汽车分配值(value)。我被迫使用单独的方法来创建这些车辆,对它们进行操作并将结果打印到控制台。在 python 中,我可能只是返回多个数组(或列表)并将它们的值分配给不同的变量,但是在 Java 中我该如何做到这一点?

最佳答案

您初始化车辆数组:

private void createVehicles() {
cars = new Car[10];
motorcycles = new Motorcycle[10];
trucks = new Truck[10];

}

但是你的数组现在只包含空汽车、空卡车......

您还需要初始化它们:

private void createVehicles() {
cars = new Car[10];
for (int i = 0; i < cars.length; i++) {
cars[i] = new Car();
}
motorcycles = new Motorcycle[10];
trucks = new Truck[10];
// Init other vehicles as well
}

关于java - 将多个 Java 对象数组传递给另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50773919/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com