2016-12-11 52 views
0

所以最近我遇到了这个问题,每次我尝试添加两个+车(卡车,公共汽车或车辆)时,程序都会获得空指针引用。看起来像我的数组只能容纳一个对象。这是为什么?数组大小设置为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++; 
    } 

在那里我accesing的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++; 
     } 
    } 
} 
+1

将代码发布到使用'Town'对象的地方。 – GurV

+0

@gurwinderSingh完成。 –

+0

我同意@GurwinderSingh。我只是用一个测试'main()'在我的机器上运行代码,然后编译并运行。我怀疑你的客户端代码坏了。请添加引发错误的方法。此外,如果需要,尽可能减少它,以便您有一个MVCE(http://stackoverflow.com/help/mcve)。 – entpnerd

回答

0

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

+0

非常感谢! –

+0

不客气。很高兴帮助。 – entpnerd

0

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

+0

如果MaxNumberOfCars超过,您将收到ArrayIndexOfBoundException –

+0

使计数变量为静态。没有改变。 –

+0

将代码发布到使用Town对象的地方。 –

相关问题