预订后显示保留时出现ArrayIndexOutOfBounds异常的错误 – Java。

我正在为我的活动做一个预订功能,我可以成功地添加参会者,但是当我想显示每个参会者的详细信息时,它给我一个ArrayIndexOutOfBounds异常错误,我不太清楚如何解决这个问题。

Main.java

private static Scanner sc = new Scanner(System.in);

private static int eventCreationLimit = 5;
private static Event[] events = new Event[eventCreationLimit];
private static int eventsCreated;

public static void main(String args[]) {
  String input;

        // Main menu.
        do {
            System.out.println("\n~ BOOKING SYSTEM ~");
            System.out.println("------------------");
            System.out.println("A. Schedule an Event");
            System.out.println("B. Add an Attendee");
            System.out.println("C. View Reservations");
            System.out.println("X. Exit\n");

            System.out.print("Select an option: ");
            input = sc.nextLine();

            switch (input.toUpperCase()) {
                case "A":
                    scheduleAnEvent();
                    break;

                case "B":
                    addAttendee();
                    break;

                case "C":
                    displayReservations();
                    break;

                case "X":
                    System.out.println("INFO: You have exited the booking system.");
                    break;

                default:
                    System.out.println("ERROR: Invalid input!");
            }
        } while (!input.equalsIgnoreCase("X"));
}

private static void scheduleAnEvent() {
        System.out.println("\n~ SCHEDULE A EVENT ~");
        System.out.println("--------------------");

        System.out.print("Enter the ID: ");
        String ID = sc.nextLine();

    ...

        System.out.print("Enter the attendee limit: ");
        int attendeeLimit = Integer.parseInt(sc.nextLine());

        // Add the new event to the array.
        events[eventsCreated++] = new Event(ID, ..., attendeeLimit, attendeeLimit, ...);

        for (int i = 0; i < eventsCreated; i++)
            // Set the places available for the specific event being created to subtract it later when an attendee is added.
            if (ID.equals(events[i].getID()))
                // The number of places available left in the event can be displayed by going to "B. View All Events".
                events[i].setPlacesAvailable(attendeeLimit);

        // Give the user a confirmation message.
        System.out.println("\nINFO: Sucessfully created Event: " + ID + ".");
    }

private static void addAttendee() {
  Event event = null;
  boolean result = false;

  System.out.println("\n~ ADD AN ATTENDEE ~");
  System.out.println("-------------------");

  System.out.print("Enter attendee name: ");
  String name = sc.nextLine();

  System.out.print("Enter attendee phone number: ");
  String phone = sc.nextLine();
  Attendee a = new Attendee(name, phone);

  System.out.print("Enter event ID: ");
  String eventID = sc.nextLine();

  // Check if the given ID matches an event.
  for (int i = 0; i < eventsCreated; i++)
    if (events[i].getID().equals(eventID))
      event = events[i];

  if (event != null) {
    if (event.getID().equals(eventID)) {
        result = ((Event) event).addAttendee(a);
        if (result) {
          // If the event has enough room, then add the attendee.
          System.out.println("INFO: Attendee successfully added to Event: " + eventID + ".");
          displayReservations();
        }
        else
          // If the event is full, then the attendee will not be added.
          System.out.println("ERROR: The Event: " + eventID + " is full, the attendee could not be added.");
    } else
      System.out.println("ERROR: The given ID does not match any existing event.");
  } else
    System.out.println("ERROR: The event was not found.");
}

private static void displayReservations() {
  System.out.println("\n~ RESERVATIONS ~");
  System.out.println("----------------");

  String pattern = "%-18s %-18s %-22s %-1s\n";

  System.out.printf(pattern, "NAME", "PHONE", "EVENT ID", "FEE");
  System.out.println("----------------------------------------------------------------");

  // Display all reservations for events.
  for (int i = 0; i < events[i].getAttendeeCount(); i++)
    events[i].displayReservations();
}

事件.java

...
private String ID;
private int attendeeLimit;
private int attendeeCount;
private int placesAvailable;
private Attendee[] a = new Attendee[attendeeCount];

public Demonstration(..., String ID, int placesAvailable, int attendeeLimit, ...) {
    this.ID = ID;
    this.placesAvailable = placesAvailable;
    this.attendeeLimit = attendeeLimit;
}

public String getID() { return this.ID; }
public int getPlacesAvailable() { return this.placesAvailable; }
public int getAttendeeLimit() { return this.attendeeLimit; }

public void setPlacesAvailable(int placesAvailable) { this.placesAvailable = placesAvailable; }

public boolean addAttendee(Attendee at) {
  // Proceed to add the attendee if there is enough room.
  if (attendeeCount <= placesAvailable) {
    attendeeCount++;

    // Decrease the number of places available by one.
    setPlacesAvailable(placesAvailable - 1);
    return true;
  }
  return false;
}

public void displayReservations() {
  System.out.println("ID: " + ID);
  if (attendeeCount > 0)
    for (int i = 0; i < attendeeCount; i++)
      a[i].attendeeDetails();
}

访客.java.Attendee.Attendee.java

private String name;
private String phone;

public Attendee(String name, String phone) {
    this.name = name;
    this.phone = phone;
}

public String getName() { return this.name; }

public String getPhone() { return this.phone; }

public void attendeeDetails() {
    System.out.println("Name: " + name);
    System.out.println("Phone: " + phone);
}

上面的代码给我一个ArrayIndexOutOfBoundsException错误,在 displayReservations() 方法 (a[i].attendeeDetails()),每当我试图将一个与会者添加到一个事件中。

问题:如何显示所有活动的所有预订详情? 如何显示所有活动的所有预订详情?谢谢您的帮助

编辑:如何显示所有活动的预约详情?

的错误。Index 0 out of bounds for length 0.

解决方案:

你的代码有几个问题。

  1. 你的代码有几个问题: 你维护的attendeeCount比起参加人数的大小是分开的。Attendee[]但在你的 addAttendee() 方法,你从来没有真正将新的出席者添加到数组中。

  2. 因为 Attendee[] 是一个数组,它不能大于第一次初始化时的大小。如果你想使用一个数组,而不是一个可以动态增长的ArrayList,你需要将数组初始化到最大尺寸。placesAvailable:

所以,我的建议是,通过导入 java.util.Arraylist,改变了声明中的 Attendee[] 到一个ArrayList,并更新Event.java代码的其余部分以使用ArrayList,以及确保你在ArrayList中添加新的出席者。addAttendee() 方法。最后,你不需要单独维护出席者人数,只要向出席者ArrayList询问它的当前大小即可。

事件.java

...
import java.util.*; //You can import all java.util classes 

private String ID;
private int attendeeLimit;
private int placesAvailable;
private List<Attendee> attendees = new ArrayList<>(); //Initialize the attendees ArrayList

public Demonstration(..., String ID, int placesAvailable, int attendeeLimit, ...) {
    this.ID = ID;
    this.placesAvailable = placesAvailable;
    this.attendeeLimit = attendeeLimit;
}

public String getID() { return this.ID; }
public int getPlacesAvailable() { return this.placesAvailable; }
public int getAttendeeLimit() { return this.attendeeLimit; }

public void setPlacesAvailable(int placesAvailable) { this.placesAvailable = placesAvailable; }

public boolean addAttendee(Attendee at) {
  // Proceed to add the attendee if there is enough room.
  if (attendeeCount <= placesAvailable) {
    attendees.add(at); //Make sure you add the new Attendee to the list

    // Decrease the number of places available by one.
    setPlacesAvailable(placesAvailable - 1);
    return true;
  }
  return false;
}

public void displayReservations() {
  System.out.println("ID: " + ID);
  int attendeeCount = attendees.size(); //Calculate the number of Attendees
  if (attendeeCount > 0)
    for (int i = 0; i < attendeeCount; i++)
      attendees.get(i).attendeeDetails();
}

给TA打赏
共{{data.count}}人
人已打赏
未分类

键盘处理 swiftui

2022-9-9 3:18:17

未分类

在DynamoDB中设计表

2022-9-9 3:18:19

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索