javaarraylist

How to check if the user has purchased the maximum capacity?


I have a Java code for booking movie tickets. In this program, each person can only buy two tickets, a maximum of 10 tickets are sold and at the end it displays a list with the names of the people. I did the whole process where I initialized with ArrayList and storing each name within that list, but I have no idea how to make this program check within the list itself if a person has already purchased more than two tickets.

Here's the code:

public class BookingTickets{

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    ArrayList<String> list = new ArrayList<>();

    int ticketsPurchased = 0;
    int allTickets = 10;

    System.out.print("Do you want to buy a ticket? (y/n): ");
    String response = sc.next().toLowerCase();

    if (response.equals("n")) {
      System.out.println("Thank you. See you next time.");     
    }

    while (response.equals("y")) {
      if (ticketsPurchased <= 2) {

        if (allTickets == 0) {
          System.out.print("Sorry, we have no more tickets!\n");
          System.out.println(list);
        } 

        System.out.print("How many tickets do you want to buy? ");
        ticketsPurchased = sc.nextInt();

        System.out.print("Enter the buyer's name: ");
        String name = sc.next();
        list.add(name);
        allTickets -= ticketsPurchased;
      } else {
        System.out.print("Limit of 2 tickets per person.");
      }

      System.out.print("Do you want to buy a ticket? (y/n): ");
      response = sc.next().toLowerCase();
    }

    System.out.println(list);
        
    sc.close();
  }
}

Solution

  • The Methode Collections.frequency(list, name) counts the number of entries with name in the list.

    It is provided by the utility class java.util.Collections.


    Besides that your code has other issues and several possible improvements.

    Issues:

    Improvements: