我正在編寫一個管理庫存的程序,例如通過添加、刪除和租用物品,所有這些都是通過在面向對象的氛圍中使用多個類來實現的。下面是我的實現類(Driver)。Driver.javapublic class Driver { public static void main(String[] args) { ABCRentals abc = new ABCRentals(); Furniture item1 = new Furniture(); boolean flag = abc.add(item1); List<Integer> idList = abc.getIDList(); String[] itemTypes = abc.getItemArray(); System.out.println("Item ID Numbers: " + Arrays.toString(idList.toArray())); System.out.println("Item Types: " + Arrays.toString(itemTypes)); }}這段代碼工作得很好,因為它能夠通過getIDList()和getItemArray()方法檢索和打印 ArrayList 和 String 數組,這些方法在ABCRentals類中指定:ABCRentals.javapublic class ABCRentals implements Inventory{ private List<Integer> idNumbers = new ArrayList<Integer>(); private List<Item> items = new ArrayList<Item>(); private List<Integer> rentedItems = new ArrayList<Integer>(); private String[] itemTypes2; public ABCRentals() { } public List<Integer> getIDList() { return idNumbers; } public List<Item> getItemList() { return items; } public String[] getItemArray() { return itemTypes2; } public List<Integer> getRentedList() { return rentedItems; } public boolean add(Item item) { if (items.size() >= 300) return false; else { idNumbers.add(idNumbers.size() + 1); items.add(item); Object[] itemTypes = items.toArray(); itemTypes2 = new String[itemTypes.length]; int dvd = 0, f = 0, tv = 0; for (int index = 0; index < itemTypes.length; index++) { String indexValue = itemTypes[index].getClass().toString().substring(6); if (indexValue.equals("DVDPlayer")) { dvd++; itemTypes2[index] = indexValue + " #" + Integer.toString(dvd); }因此,當我嘗試從類中訪問 ArrayList 和數組的內容時Driver,它可以工作。但是,當我嘗試從任何其他類訪問 ArrayList 或數組時,無論是DVDPlayer、Furniture或Television類,我都會收到NullPointerException錯誤,因此換句話說,ArrayList 和數組不會使用類中指定的值進行更新/Driver填充與上面不同的是,該add()方法返回為空。
1 回答

喵喵時光機
TA貢獻1846條經驗 獲得超7個贊
您在 main 中調用 add() 方法,該方法實例化 itemTypes2 數組。在訪問 Furniture 類中的 itemTypes2 之前,您不會調用 add() ,因此它為 null。
添加回答
舉報
0/150
提交
取消