类对象数组只能获得一个对象

时间:2016-12-11 09:01:49

标签: java arrays

所以最近我遇到了这个问题,每次我尝试添加两辆+汽车(卡车,公共汽车或车辆)程序都会获得空指针参考。好像我的数组只能容纳一个对象。这是为什么?数组大小设置为200 ...添加一个对象就像一个魅力。这也适用于C#。但不是用Java。

public class Town {

    public int MaxNumberOfCars = 200;
    public String Dealership;
    public String Adress;
    public String Phone;
    public Car[] Cars = new Car[MaxNumberOfCars];
    public Bus[] Busses = new Bus[MaxNumberOfCars];
    public Truck [] Trucks = new Truck[MaxNumberOfCars];
    public Vehicles[] Vehicles = new Vehicles[MaxNumberOfCars];
    public static int carCount;
    public static int busCount;
    public static int truckCount;
    public static int vehicleCount;
    public int townVehicleCount;
    public int DealershipCount;
    public double avgage;


    public Town(String dealership, String adress, String phone) {
        Dealership = dealership;
        Adress = adress;
        Phone = phone;
    }

    public void AddCar(Car car) {
        Cars[carCount++] = car;
        vehicleCount++;
    }

我正在访问AddCar的代码:

private static void Read(String text, Town[] towns) {
    String text1 = text;
    String dealership = null, adress = null, phone = null;

    ArrayList<String> line = new ArrayList<>();
    StringTokenizer st = new StringTokenizer(text1, "\n");
    int count = st.countTokens()-3;
    if (line != null) {
        dealership = st.nextToken();
        adress = st.nextToken();
        phone = st.nextToken();

        towns[townCount] = new Town(dealership, adress, phone);

        for(int i = 0; i < count; i++) {

            String string = st.nextToken();
            String[] values = string.split(";");
            String licenseplates = values[0]; // 004
            char type = values[1].charAt(0);
            String brand = values[2];
            String model = values[3];
            YearMonth yearofmake = YearMonth.parse(values[4]);
            YearMonth techinspection = YearMonth.parse(values[5]);
            String fuel = values[6];
            int fuelconsumption = Integer.valueOf(values[7]);
            switch (type) {
                case 'c':
                    Car car = new Car(licenseplates, brand, model, yearofmake, techinspection, fuel, fuelconsumption);
                    towns[townCount].AddCar(car);
                    towns[townCount].AddVehicle(car);
                    break;
            }
            townCount++;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

为什么计数变量是静态的? 我想首先你必须改变这一点。那么你必须添加一些验证,比如在你的addCar方法中检查MaxNumberOfCars验证。

答案 1 :(得分:0)

您的问题是,如果您的阵列townCount中没有足够的城镇,那么您正在递增towns。您需要在阵列中添加更多城镇,或者在for循环结束时删除townCount++;行。