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.
The program should start with an empty list and a maximum of 10 tickets available.
At each iteration, ask the user if they want to buy a ticket.
If the user wants to buy, ask for their name and add them to the list if there are still tickets available.
If the tickets are sold out, display a sold out message.
At the end, display the list of all people who bought 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();
}
}
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:
if (ticketsPurchased <= 2)
is wrong. You can only count the already bought tickets, after the buyer name is entered - and then first count the occurences in the list and if it is lower(!) than 2 let the purchase happen.Improvements:
list
only as List<String>
. Which implementation of List
you actually use doesn't matter for the rest of the code and this way it is easier to swap for other implementations of List
if you need to or want to try it out. (List<String> list = new ArrayList<>();
)"Thank you. See you next time."
simply after the loop, you don't need to put it into an if
.