1

I'm making a reservation feature for my events, and I can successfully add the attendee, however when I want to display the details for every attendee, it gives me a ArrayIndexOutOfBounds exception error, which I'm not quite sure how to fix.

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();
}

Event.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();
}

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);
}

The above code gives me a ArrayIndexOutOfBoundsException error in the displayReservations() method (a[i].attendeeDetails()) whenever I try to add an attendee to an event.

Problem: How do I display all reservation details for all events? Thank you for your help!

EDIT

The error: Index 0 out of bounds for length 0.

Wolfizzy
  • 581
  • 1
  • 4
  • 18
  • Can you post the exception details? – pczeus Apr 24 '20 at 12:28
  • I don't see anywhere in your code a place where you actually assign any elements to the `a` array, eg.: `a[i] = new Attendee()`, All elements of the array are null. – Amongalen Apr 24 '20 at 12:31
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Sudhir Ojha Apr 24 '20 at 12:31
  • @Amongalen in `Main.java`, I have user input where the elements are assigned to the `a` array. – Wolfizzy Apr 24 '20 at 12:39
  • Point me the line which in your opinion sets anything in `a` array. (terrible variable name btw.) – Amongalen Apr 24 '20 at 12:42
  • @pczeus I've edited the question to include the error. I've realized that I pointed the wrong error; it was an ArrayIndexOutOfBounds error, not a NullPointerException error. Sorry about that! – Wolfizzy Apr 24 '20 at 12:44
  • @Amongalen my bad, it wasn't assigned to the `a` array; I stored it elsewhere. – Wolfizzy Apr 24 '20 at 12:50

2 Answers2

0

attendeCount does not have a value as at the time you creating the Array "a". For what you are trying to achieve, I suggest:

i. Use an Arraylist. ii. Initialize you array in the constructor to attendeLimit.

If possible, I also suggest you use parameter methods where neccessary.

0

There are a couple of issues with your code:

  1. You are maintaining an attendeeCount separately than the size of the Attendee[], but in your addAttendee() method, you never actually add the new Attendee to the array

  2. Because Attendee[] is an array, it can't grow larger than the size when first initialized. If you want to use an array, instead of an ArrayList that can grow dynamically, you need to initialize the array to the maximum size: placesAvailable:

So, my recommendation would be to switch from using an array to an ArrayList by importing java.util.Arraylist, changing the declaration of the Attendee[] to an ArrayList, and updating the rest of the Event.java code to use the ArrayList, as well as making sure you add the new Attendee in the addAttendee() method. Finally, you don't need to maintain the attendee count separately, just ask the attendees ArrayList it's current size.

Event.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();
}
pczeus
  • 7,709
  • 4
  • 36
  • 51