我想創(chuàng)建一個小型停車系統(tǒng),有四個類:一個用于用戶輸入,一個用 ArrayList (CarPark) 維護停車位列表,一個 ParkingSlot 類和一個汽車類。用戶菜單中的選項之一是將汽車停放在現(xiàn)有的停車位中。為此,用戶需要輸入汽車的車牌號碼。接下來,汽車應該停在停車場,并且 ArrayList 應該更新。首先,用戶創(chuàng)建 ParkingSlot 作為 CarPark 中 ArrayList 的對象。該對象中包含類 Car,該類為“null”。用戶界面菜單的選項允許用戶將汽車停放在創(chuàng)建的槽位中。在這里,我很難以將汽車分配到特定插槽的方式對系統(tǒng)進行編程。分配后,當調(diào)用 CarPark 類中的方法 listSlots 時,汽車應該出現(xiàn)在插槽 Id 旁邊。在 arrayList 中創(chuàng)建點的應用程序類的一部分:if (choice == 1) {System.out.println("Enter an ID of the type \"D##\""); input = scanner.nextLine(); if(input.matches("[D][0-9]{2}")) { if (carParkObj.hasParkingSlot(input) == false) { carParkObj.addParkingSlot(input, "Visitor"); } else { System.out.println("Invalid Input. This slotID alreasy exists!"); } break; } else { System.out.println("Invalid Input"); } break;}應用程序類中進行汽車注冊的部分:else if (choice == 4) { System.out.println("Enter the car registration number of the type \"A1234\" "); input = scanner.nextLine(); if(input.matches("[A-Z][0-9]{4}")) { String newRegistrationNumber = input; System.out.println("Enter owner's name"); String newOwner = scanner.nextLine(); System.out.println("Is the owner Visitor or Staff member? For enter \"V\" for Visitor or \"S\" for staff member."); input = scanner.nextLine(); if (input.equals("V")) { boolean staffMember = false; Car car = new Car(newRegistrationNumber, newOwner, staffMember); //not sure that method do I need here to add the car to the Slot with the particular ID else { System.out.println("Invalid Input"); } }else { System.out.println("Invalid Input"); break;}
1 回答

撒科打諢
TA貢獻1934條經(jīng)驗 獲得超2個贊
將汽車分配給特定槽位的快速而骯臟的方法是迭代槽位的 ArrayList,直到找到具有所需 ID 的槽位,這與刪除停車位的方法相同。
一種更簡潔的方法是將停車位存儲為 a Map<String, ParkingSlot>
,其中鍵是停車位的 ID,值是停車位本身。然后您可以通過其 ID 簡單地訪問該插槽。
由于 Map 的鍵是一組,因此這也為您提供了一種快速檢查重復 ID 的方法。
添加回答
舉報
0/150
提交
取消