简体   繁体   English

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

[英]Passing multiple arrays of Java objects to another method

I just started learning java, with some minor prior experience in python and a bit of javascript, but not using classes. 我刚开始学习Java,但在python和javascript方面有少量的先验经验,但是没有使用类。 I have an issue with this code (just for reference, below that I point out exact issue): 我的代码有问题(仅供参考,下面我指出确切的问题):

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();
    }
}

This code compiles (classes Car, Motorcycle and Truck are defined in my code as well, but are not relevant to the question), however I get runtime null pointer exception on 该代码进行编译(在我的代码中也定义了汽车,摩托车和卡车类,但与该问题无关),但是我在运行时得到空指针异常

   for (Car car : cars) { // null pointer exception here
        for (int i = 0; i < 50; i++) {
            car.moveForAnHour();
        }
    }

so I guess I am not assigning value to cars properly. 所以我想我没有为汽车正确分配价值。 I am forced to have separate methods to create those vehicles, operate on them and print the results to console. 我被迫使用单独的方法来创建这些载具,对其进行操作并将结果打印到控制台。 In python I'd probably just return multiple arrays (or lists) and assign their values to different variables, but how do I do it here in Java? 在python中,我可能只是返回多个数组(或列表),并将它们的值分配给不同的变量,但是在Java中该如何做呢?

initial arrays in constructor 构造函数中的初始数组

public Race() {
  createVehicles();
}

You initialize your vehicle array: 您初始化车辆数组:

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

}

But your array now contains only null-car, null-trucks... 但是您的数组现在仅包含空车,空卡车...

You need to initialize them as well: 您还需要初始化它们:

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
}

You are creating cars variable to hold 10 instances of Car but not storing any value. 您正在创建cars变量,以容纳10个Car实例,但不存储任何值。 Add some values to the array and try. 将一些值添加到数组,然后尝试。

when you initial an array you fill the array with nulls. 当您初始化数组时,将使用空值填充数组。 so Car[] cars = new Car[10]; 所以Car [] cars = new Car [10]; means you have an array with 10 nulls in it. 表示您有一个包含10个null的数组。 and you are iterating on it. 而您正在对此进行迭代。 and you will get NullPointerException here car.moveForAnHour(); 您将在此处获得NullPointerException car.moveForAnHour(); in createVehicles() you must fill it with objects. 在createVehicles()中,必须用对象填充它。 for example : 例如 :

private void createVehicles() {
    cars = new Car[10];
    for(int i = 0; i < cars.length; i++) {
      cars[i] = new Car();
    }

} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM