所以最近我遇到了這個問題,每次我嘗試添加兩個+車(卡車,公共汽車或車輛)時,程序都會獲得空指針引用。看起來像我的數組只能容納一個對象。這是爲什麼?數組大小設置爲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++;
}
}
}
將代碼發佈到使用'Town'對象的地方。 – GurV
@gurwinderSingh完成。 –
我同意@GurwinderSingh。我只是用一個測試'main()'在我的機器上運行代碼,然後編譯並運行。我懷疑你的客戶端代碼壞了。請添加引發錯誤的方法。此外,如果需要,儘可能減少它,以便您有一個MVCE(http://stackoverflow.com/help/mcve)。 – entpnerd