为了账号安全,请及时绑定邮箱和手机立即绑定

在 ArrayList 中为现有条目设置值

在 ArrayList 中为现有条目设置值

慕哥9229398 2023-07-28 15:25:36
我想创建一个小型停车系统,有四个类:一个用于用户输入,一个用 ArrayList (CarPark) 维护停车位列表,一个 ParkingSlot 类和一个汽车类。用户菜单中的选项之一是将汽车停放在现有的停车位中。为此,用户需要输入汽车的车牌号码。接下来,汽车应该停在停车场,并且 ArrayList 应该更新。首先,用户创建 ParkingSlot 作为 CarPark 中 ArrayList 的对象。该对象中包含类 Car,该类为“null”。用户界面菜单的选项允许用户将汽车停放在创建的槽位中。在这里,我很难以将汽车分配到特定插槽的方式对系统进行编程。分配后,当调用 CarPark 类中的方法 listSlots 时,汽车应该出现在插槽 Id 旁边。在 arrayList 中创建点的应用程序类的一部分: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条经验 获得超2个赞

将汽车分配给特定槽位的快速而肮脏的方法是迭代槽位的 ArrayList,直到找到具有所需 ID 的槽位,这与删除停车位的方法相同。

一种更简洁的方法是将停车位存储为 a Map<String, ParkingSlot>,其中键是停车位的 ID,值是停车位本身。然后您可以通过其 ID 简单地访问该插槽。

由于 Map 的键是一组,因此这也为您提供了一种快速检查重复 ID 的方法。


查看完整回答
反对 回复 2023-07-28
  • 1 回答
  • 0 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信