Movie Ticket Booking using DSA

Building a Movie Ticket Booking System: A Comprehensive Java Implementation Guide

Class Declaration

public class MovieTicketBookingSystem {

This declares a public class named MovieTicketBookingSystem. This is the main class that contains all the logic for the movie ticket booking system.

Static Variables

static int bookedSeat = 0;
static int prizeOfTicket = 0;
static int totalIncome = 0;
static int row;
static int seats;
static int totalSeat;
static String[][] bookedTicketPerson;
static HashMap<String, HashMap<String, String>> tableOfChart;
static HashMap<String, String> users;

static String currentUser;

These are static variables that will be used throughout the class:

  • bookedSeat: Keeps track of the number of booked seats.

  • prizeOfTicket: Stores the price of the ticket for the current booking operation.

  • totalIncome: Accumulates the total income from all booked tickets.

  • row: Stores the number of rows in the seating arrangement.

  • seats: Stores the number of seats per row.

  • totalSeat: Stores the total number of seats in the cinema.

  • bookedTicketPerson: A 2D array that stores information about each booked ticket.

  • tableOfChart: A HashMap that represents the seating chart, showing which seats are booked or available.

  • users: A HashMap that stores usernames and passwords for login purposes.

  • currentUser: A string that stores the username of the currently logged-in user.

Explanation of Static Blocks and Initialization

Static variables are initialized here, and in a later block, a static initializer block will be used to pre-populate the users HashMap with admin credentials.

Inner ClassChart

static class Chart {
    static HashMap<String, HashMap<String, String>> chartMaker() {
        HashMap<String, HashMap<String, String>> seatsChart = new HashMap<>();
        for (int i = 0; i < row; i++) {
            HashMap<String, String> seatsInRow = new HashMap<>();
            for (int j = 0; j < seats; j++) {
                seatsInRow.put(Integer.toString(j + 1), "A");
            }
            seatsChart.put(Integer.toString(i), seatsInRow);
        }
        return seatsChart;
    }

    static double findPercentage() {
        return (double) (bookedSeat * 100) / totalSeat;
    }
}

Let's break down the Chart class and explain the structure of the HashMap used.

Inner Class Chart

The Chart class contains two static methods that help manage the seating chart and calculate booking statistics.

chartMaker() Method

static HashMap<String, HashMap<String, String>> chartMaker() {
    HashMap<String, HashMap<String, String>> seatsChart = new HashMap<>();
    for (int i = 0; i < row; i++) {
        HashMap<String, String> seatsInRow = new HashMap<>();
        for (int j = 0; j < seats; j++) {
            seatsInRow.put(Integer.toString(j + 1), "A");
        }
        seatsChart.put(Integer.toString(i), seatsInRow);
    }
    return seatsChart;
}
  • Purpose: This method initializes the seating chart for the cinema.

  • Functionality:

    • It creates a new HashMap called seatsChart, which will store the seating arrangement.

    • It loops through each row (for (int i = 0; i < row; i++)).

    • For each row, it creates another HashMap called seatsInRow to store the seats in that row.

    • It then loops through each seat in the row (for (int j = 0; j < seats; j++)).

    • For each seat, it puts an entry in seatsInRow with the seat number as the key (converted to a string) and "A" as the value, indicating the seat is available.

    • After initializing all seats in a row, it puts this seatsInRow map into the seatsChart with the row number as the key (converted to a string).

    • Finally, it returns the seatsChart map.

findPercentage() Method

static double findPercentage() {
    return (double) (bookedSeat * 100) / totalSeat;
}
  • Purpose: This method calculates the percentage of seats that have been booked.

  • Functionality:

    • It returns the ratio of booked seats to total seats, multiplied by 100 to convert it to a percentage.

Structure of the HashMap

The chartMaker() method creates a nested HashMap structure that represents the seating chart. Here is the structure explained:

  • Outer HashMap (seatsChart):

    • Key: String representing the row number (e.g., "0", "1", "2", ...).

    • Value: Another HashMap representing the seats in that row.

  • Inner HashMap (seatsInRow):

    • Key: String representing the seat number in the row (e.g., "1", "2", "3", ...).

    • Value: String representing the status of the seat ("A" for available, "B" for booked).

Example Structure

For a cinema with 3 rows and 3 seats per row, the structure would look like this:

  • seatsChart (outer HashMap):

    • Key: "0" -> Value: seatsInRow for row 0

      • Key: "1" -> Value: "A"

      • Key: "2" -> Value: "A"

      • Key: "3" -> Value: "A"

    • Key: "1" -> Value: seatsInRow for row 1

      • Key: "1" -> Value: "A"

      • Key: "2" -> Value: "A"

      • Key: "3" -> Value: "A"

    • Key: "2" -> Value: seatsInRow for row 2

      • Key: "1" -> Value: "A"

      • Key: "2" -> Value: "A"

      • Key: "3" -> Value: "A"

Visualization

seatsChart
|
|-- "0" -> { "1" : "A", "2" : "A", "3" : "A" }
|
|-- "1" -> { "1" : "A", "2" : "A", "3" : "A" }
|
|-- "2" -> { "1" : "A", "2" : "A", "3" : "A" }

In this example, each row (represented by the keys "0", "1", "2") contains a HashMap where each seat (represented by the keys "1", "2", "3") is initially marked as "A" (available).

This nested HashMap structure allows for easy access and modification of seat statuses by specifying the row and seat numbers.

Let's break down the segment of code, which focuses on user management, including hardcoded admin credentials, user creation, and login validation.

Static Block for Initialising Admin Credentials

// Initialize hardcoded admin credentials
static {
    users = new HashMap<>();
    users.put("admin", "password");
}
  • Purpose: This block initializes the usersHashMap and adds a default admin user with hardcoded credentials.

  • Functionality:

    • users is a HashMap that will store username-password pairs.

    • The static block runs once when the class is first loaded.

    • users.put("admin", "password"); adds an entry to the users map with "admin" as the username and "password" as the password.

    • This ensures that there's always an admin user with predefined credentials.

createUser Method

// Method to create a new user
static void createUser(String username, String password) {
    users.put(username, password);
    System.out.println("User created successfully!");
}
  • Purpose: This method allows the creation of new users by adding their credentials to the usersHashMap.

  • Functionality:

    • users.put(username, password); adds a new entry to the users map with the provided username and password.

    • System.out.println("User created successfully!"); prints a confirmation message to the console.

login Method

// Method to validate login credentials
static boolean login(String username, String password) {
    return users.containsKey(username) && users.get(username).equals(password);
}
  • Purpose: This method validates the login credentials provided by the user.

  • Functionality:

    • users.containsKey(username) checks if the username exists in the users map.

    • users.get(username).equals(password) retrieves the password associated with the username and checks if it matches the provided password.

    • The method returns true if both conditions are met (the username exists and the password is correct); otherwise, it returns false.

The main method is the entry point of the program. It allows users to input the number of rows and seats in each row for the movie theater's seating arrangement. Let's break down what each part does:

  1. Initialization:

     Scanner scanner = new Scanner(System.in);
    
    • Creates a new Scanner object named scanner to receive input from the user.
  2. User Input for Rows and Seats:

     System.out.println("Enter number of Rows: ");
     row = scanner.nextInt();
     System.out.println("Enter number of seats in a Row: ");
     seats = scanner.nextInt();
    
    • Prompts the user to enter the number of rows and the number of seats in each row.

    • Reads the input values using scanner.nextInt() and assigns them to the variables row and seats, respectively.

  3. Total Seats Calculation:

     totalSeat = row * seats;
    
    • Calculates the total number of seats in the movie theater by multiplying the number of rows (row) with the number of seats in each row (seats).
  4. Initialization of Arrays and HashMap:

     bookedTicketPerson = new String[row][seats];
     tableOfChart = Chart.chartMaker();
    
    • Initializes the bookedTicketPerson array to store information about booked tickets, with dimensions based on the number of rows and seats.

    • Calls the chartMaker() method from the Chart class to initialize the tableOfChart HashMap, which represents the seating arrangement with rows and seats.

      Let's walk through an example interaction with the program.

        Enter number of Rows: 
        5
        Enter number of seats in a Row: 
        6
      

      After running the program, the user is prompted to enter the number of rows and the number of seats in each row. Here, the user inputs 5 rows and 6 seats in each row.

      The program then calculates the total number of seats as 5 * 6 = 30.

      It initializes the arrays and HashMap based on the provided number of rows and seats.

      bookedTicketPerson Array Initialization:

        // Example: 5 rows and 6 seats in each row
        String[][] bookedTicketPerson = new String[5][6];
      

      After initialization, bookedTicketPerson would look like this:

        [ [null, null, null, null, null, null],
          [null, null, null, null, null, null],
          [null, null, null, null, null, null],
          [null, null, null, null, null, null],
          [null, null, null, null, null, null] ]
      

      Each element in the array represents a seat in the theater. Since no tickets are booked yet, all elements are initialized to null.

      tableOfChart HashMap Initialization:

        // Example: 5 rows and 6 seats in each row
        HashMap<String, HashMap<String, String>> tableOfChart = Chart.chartMaker();
      

      After initialization, tableOfChart would be populated as follows:

        {
          "0": { "1":"A", "2":"A", "3":"A", "4":"A", "5":"A", "6":"A" },
          "1": { "1":"A", "2":"A", "3":"A", "4":"A", "5":"A", "6":"A" },
          "2": { "1":"A", "2":"A", "3":"A", "4":"A", "5":"A", "6":"A" },
          "3": { "1":"A", "2":"A", "3":"A", "4":"A", "5":"A", "6":"A" },
          "4": { "1":"A", "2":"A", "3":"A", "4":"A", "5":"A", "6":"A" }
        }
      

      Each key in tableOfChart represents a row number, and its corresponding value is another HashMap representing the seats in that row. The seat numbers are the keys, and their statuses ("A" for available) are the values.

The next part of the code implements a loop that continuously prompts the user for options, allowing them to log in, create a new user, or exit the system.

while (true) {
  • This line starts an infinite loop. It ensures that the program keeps running until explicitly terminated.
System.out.println("Welcome to Movie Ticket Booking System");
System.out.println("1. Log in");
System.out.println("2. Create a new user");
System.out.println("0. Exit");
System.out.print("Select option: ");
  • These lines print the welcome message and the options menu for the user.

  • Users are prompted to select an option: login, create a new user, or exit the program.

int option = scanner.nextInt();
scanner.nextLine(); // Consume newline
  • This code snippet reads the user's input from the console and stores it in the option variable.

  • scanner.nextInt() reads the integer input.

  • scanner.nextLine() is used to consume the newline character left in the input buffer after nextInt().

if (option == 0) {
    System.out.println("Exiting...");
    break;
}
  • This if statement checks if the user chose to exit the program.

  • If the user entered 0, the program displays "Exiting..." and breaks out of the loop, terminating the program.

switch (option) {
    case 1:
        // Log in
        System.out.print("Username: ");
        String loginUsername = scanner.nextLine();
        System.out.print("Password: ");
        String loginPassword = scanner.nextLine();
        if (login(loginUsername, loginPassword)) {
            currentUser = loginUsername;
            System.out.println("Login successful!");
            runBookingSystem(scanner);
        } else {
            System.out.println("Invalid username or password.");
        }
        break;
  • This switch statement handles the different options chosen by the user.

  • Case 1 is for logging in.

  • The program prompts the user to enter their username and password.

  • It then checks if the login credentials are valid using the login method.

  • If the login is successful, it sets the currentUser variable to the logged-in username and calls the runBookingSystem method to proceed with the booking system.

  • If the login fails, it displays an error message.

case 2:
    // Create a new user
    System.out.print("Enter new username: ");
    String newUsername = scanner.nextLine();
    if (users.containsKey(newUsername)) {
        System.out.println("Username already exists. Please choose a different username.");
        continue;
    }
    System.out.print("Enter new password: ");
    String newPassword = scanner.nextLine();
    createUser(newUsername, newPassword);
    break;
  • Case 2 is for creating a new user.

  • The program prompts the user to enter a new username and checks if it already exists.

  • If the username already exists, it displays an error message and continues to the next iteration of the loop.

  • If the username is available, the program prompts the user to enter a new password and then calls the createUser method to create the new user.

default:
    System.out.println("Invalid option. Exiting...");
    break;
  • This default block handles cases where the user enters an invalid option.

  • It displays an error message and breaks out of the loop, terminating the program.

Let's break down the runBookingSystem method in detail:

static void runBookingSystem(Scanner scanner) {
  • This method is responsible for running the booking system based on the current user's privileges.

  • It takes a Scanner object as input to read user input from the console.

while (true) {
  • This line starts an infinite loop, ensuring that the booking system keeps running until explicitly terminated.
if (currentUser.equals("admin")) {
  • This if statement checks if the current user is the admin.

  • Depending on whether the current user is the admin or a regular user, different options will be presented.

System.out.println("1. Show the seats\n2. Statistics\n" +
                    "3. Show booked Tickets User Info\n4. Show all booked Tickets User Info\n5. Logout\n0. Exit");
  • If the current user is the admin, this line prints the options menu tailored for the admin.

  • Admins can choose to show the seats, view statistics, view booked ticket user info, view all booked ticket user info, logout, or exit.

System.out.println("1. Show the seats\n2. Buy a Ticket\n3. Logout\n0. Exit");
  • If the current user is not the admin, this line prints the options menu tailored for regular users.

  • Regular users can choose to show the seats, buy a ticket, logout, or exit.

System.out.print("Select Option: ");
int option = scanner.nextInt();
  • This code snippet prompts the user to select an option from the menu and reads the user's input.
if (option == 0) {
    System.out.println("Exiting...");
    break;
}
  • If the user chooses to exit (enters 0), the program displays "Exiting..." and breaks out of the loop, terminating the booking system.
if (currentUser.equals("admin")) {
     System.out.println("1. Show the seats\n2. Statistics\n" +
                        "3. Show booked Tickets User Info\n4. Show all booked Tickets User Info\n5. Logout\n0. Exit")
} else {
    System.out.println("1. Show the seats\n2. Buy a Ticket\n3. Logout\n0. Exit");
}
  • Depending on whether the current user is the admin or a regular user, the program executes different blocks of code.
System.out.print("Select Option: ");
            int option = scanner.nextInt();
            if (option == 0) {
                System.out.println("Exiting...");
                break;
            } else if (currentUser.equals("admin")) {
                if (option == 1) {
                    showSeats();
                } else if (option == 2) {
                    showStatistics();
                } else if (option == 3) {
                    showBookedTicketUserInfo(scanner);
                } else if (option == 4) {
                    showAllBookedTicketUserInfo();
                } else if (option == 5) {
                    System.out.println("Logging out...");
                    currentUser = null;
                    break;
                } else {
                    System.out.println("*** Invalid Input ***");
                }
            } else {
                if (option == 1) {
                    showSeats();
                } else if (option == 2) {
                    buyTicket(scanner);
                } else if (option == 3) {
                    System.out.println("Logging out...");
                    currentUser = null;
                    break;
                } else {
                    System.out.println("*** Invalid Input ***");
                }
            }
  • This block of code handles the user's selected option.

  • If the option is 1, it calls the showSeats method to display the seating arrangement.

  • Depending on the user type (regular user or admin), option 2 may correspond to buying a ticket or showing statistics.

  • Option 3 is for logging out for user.

  • Option 4 is for showing booked ticket user info, applicable only to the admin.

  • Option 5 is for logging out, applicable only to the admin.

  • If the user enters an invalid option, it displays an error message.

Sure, let's break down the showSeats method:

static void showSeats() {
  • This line declares a method named showSeats. It's static, meaning it belongs to the class rather than an instance of the class. It does not return any value (void).
for (int seat = 0; seat < seats; seat++) {
    System.out.print(seat + " ");
}
System.out.println(seats);
  • This loop prints the seat numbers for each seat in a row. It iterates from 0 to seats - 1 (assuming seat numbering starts from 0) and prints the seat number followed by a space. After printing all seat numbers in the row, it prints the total number of seats in that row.
for (String num : tableOfChart.keySet()) {
    System.out.print((Integer.parseInt(num) + 1) + " ");
    for (String no : tableOfChart.get(num).values()) {
        System.out.print(no + " ");
    }
    System.out.println();
}
  • This loop iterates over the keys of the tableOfChart hashmap, which represent the row numbers. For each row, it prints the row number (parsed to an integer and incremented by 1 to match human-readable numbering).

  • Within each row, it iterates over the values of the hashmap entry, which represent the seat statuses ("A" for vacant and "B" for booked). For each seat, it prints the status followed by a space.

  • After printing all seats in the row, it moves to the next line to start the next row.

    Let's continue with an previous example of a seating arrangement with 3 rows and 4 seats in each row, and all seats are initially vacant. Here's the tableOfChart hashmap:

      tableOfChart = {
          "0": {"1": "A", "A": "A", "3": "A", "4": "A"},
          "1": {"1": "A", "2": "A", "3": "A", "4": "A"},
          "2": {"1": "A", "2": "A", "3": "A", "4": "A"}
      };
    

    Now, let's execute the loop:

      for (String num : tableOfChart.keySet()) {
          System.out.print((Integer.parseInt(num) + 1) + " ");
          for (String no : tableOfChart.get(num).values()) {
              System.out.print(no + " ");
          }
          System.out.println();
      }
    

    The output would be:

      1 A A A A 
      2 A A A A 
      3 A A A A
    

    Explanation:

    • The outer loop iterates over the keys of the tableOfChart hashmap, which represent the row numbers ("0", "1", "2").

    • For each row, it prints the row number incremented by 1 to match human-readable numbering.

    • Inside the inner loop, it iterates over the values of the hashmap entry, which represent the seat statuses ("S" for vacant).

    • For each seat in the row, it prints the seat status followed by a space.

    • After printing all seats in the row, it moves to the next line to start the next row.

This output provides a clear representation of the seating arrangement, showing the row numbers, seat statuses (vacant), and the arrangement of seats in each row.

System.out.println("Vacant Seats = " + (totalSeat - bookedSeat) + "\n");
  • This line prints the total number of vacant seats by subtracting the number of booked seats (bookedSeat) from the total number of seats (totalSeat). It then prints a newline character to separate the seating chart from other output.

This method effectively displays the seating arrangement, showing the seat numbers, their status (vacant or booked), and the total number of vacant seats.

Let's demonstrate an example of the showSeats method with a hypothetical seating arrangement:

Suppose we have 3 rows and 4 seats in each row. Initially, all seats are vacant.

row = 3;
seats = 4;
totalSeat = row * seats;
bookedSeat = 0;

// Assume tableOfChart is initialized with all seats vacant (represented by "S")
tableOfChart = {
    "0": {"1": "A", "2": "A", "3": "A", "4": "S"},
    "1": {"1": "A", "2": "A", "3": "A", "4": "A"},
    "2": {"1": "A", "2": "A", "3": "A", "4": "A"}
};

Calling the showSeats method would produce the following output:

0 1 2 3 4
1 A A A A 
2 A A A A 
3 A A A A 

Vacant Seats = 12

Explanation:

  • The first row displays seat numbers from 0 to 4, indicating four seats in the row.

  • Subsequent rows display the row number followed by the status of each seat ("A" for vacant).

  • In this example, all seats are vacant, so "A" is displayed for each seat.

  • The last line shows the total number of vacant seats, which is calculated by subtracting the booked seats from the total number of seats (totalSeat - bookedSeat).

Let's break down the showStatistics method:

static void showStatistics() {
  • This line declares a method named showStatistics. It's static, meaning it belongs to the class rather than an instance of the class. It does not return any value (void).
System.out.println("Number of purchased Tickets - " + bookedSeat);
  • This line prints the number of purchased tickets, which is stored in the bookedSeat variable. It concatenates the number of purchased tickets with the string "Number of purchased Tickets - " and prints the result.
System.out.println("Percentage - " + Chart.findPercentage() + "%");
  • This line prints the percentage of booked seats relative to the total number of seats. It calls the findPercentage method from the Chart class to calculate the percentage and concatenates the result with the string "Percentage - " and "%", then prints the result.
System.out.println("Current Income - $" + prizeOfTicket);
  • This line prints the current income generated from ticket sales. It concatenates the current income (prizeOfTicket) with the string "Current Income - $" and prints the result.
System.out.println("Total Income - $" + totalIncome);
  • This line prints the total income generated from all ticket sales. It concatenates the total income (totalIncome) with the string "Total Income - $" and prints the result.

This method effectively displays various statistics related to ticket sales and income in the booking system.

Let's break down the buyTicket method step by step:

Certainly! Let's break down each line of the buyTicket method with detailed explanations:

static void buyTicket(Scanner scanner) {
  • static void buyTicket(Scanner scanner) {: This line declares a static method named buyTicket that takes a Scanner object as input. This method is responsible for handling the ticket booking process.
System.out.println("Enter Row Number: ");
int rowNumber = scanner.nextInt();
  • System.out.println("Enter Row Number: ");: This line prints a message to prompt the user to enter the row number for the seat they want to book.

  • int rowNumber = scanner.nextInt();: This line reads an integer input from the user using the Scanner object scanner and assigns it to the variable rowNumber, representing the row number entered by the user.

System.out.println("Enter Column Number: ");
int columnNumber = scanner.nextInt();
  • System.out.println("Enter Column Number: ");: This line prints a message to prompt the user to enter the column number for the seat they want to book.

  • int columnNumber = scanner.nextInt();: This line reads an integer input from the user using the Scanner object scanner and assigns it to the variable columnNumber, representing the column number entered by the user.

if (rowNumber >= 1 && rowNumber <= row && columnNumber >= 1 && columnNumber <= seats) {
  • if (rowNumber >= 1 && rowNumber <= row && columnNumber >= 1 && columnNumber <= seats) {: This line checks if the entered rowNumber and columnNumber are within valid ranges. It ensures that the row number is between 1 and the total number of rows (row), and the column number is between 1 and the total number of seats in a row (seats).
if (tableOfChart.get(Integer.toString(rowNumber - 1)).get(Integer.toString(columnNumber)).equals("S")) {
  • if (tableOfChart.get(Integer.toString(rowNumber - 1)).get(Integer.toString(columnNumber)).equals("S")) {: This line checks if the seat at the specified rowNumber and columnNumber is vacant. It accesses the corresponding entry in the tableOfChart HashMap using the row and column numbers and checks if the value is equal to "S", indicating that the seat is available.
if (row * seats <= 60) {
    prizeOfTicket = 10;
} else if (rowNumber <= row / 2) {
    prizeOfTicket = 10;
} else {
    prizeOfTicket = 8;
}
  • These lines determine the base ticket price based on theater occupancy and seat location:

    • If the total number of seats (row * seats) is less than or equal to 60, or if the row number is less than or equal to half of the total rows (row / 2), the base ticket price is set to $10.

    • Otherwise, the base ticket price is set to $8.

double vacantPercentage = ((double) (totalSeat - bookedSeat) / totalSeat) * 100;
  • double vacantPercentage = ((double) (totalSeat - bookedSeat) / totalSeat) * 100;: This line calculates the percentage of vacant seats in the theater. It subtracts the number of booked seats (bookedSeat) from the total number of seats (totalSeat), divides the result by the total number of seats, and then multiplies by 100 to get the percentage.
if (vacantPercentage <= 20) {
    prizeOfTicket *= 1.3;
} else if (vacantPercentage <= 50) {
    prizeOfTicket *= 1.2;
}
  • These lines adjust the ticket price based on the percentage of vacant seats:

    • If the vacant percentage is 20% or less, the ticket price is increased by 30% (multiplied by 1.3).

    • If the vacant percentage is less than or equal to 50%, the ticket price is increased by 20% (multiplied by 1.2).

System.out.println("Ticket Price - $" + prizeOfTicket);
System.out.println("Confirm booking (yes/no): ");
String confirm = scanner.next();
  • These lines prompt the user to confirm the booking and read their input:

    • System.out.println("Ticket Price - $" + prizeOfTicket);: Prints the calculated ticket price to the console.

    • System.out.println("Confirm booking (yes/no): ");: Prompts the user to confirm the booking by entering "yes" or "no".

    • String confirm = scanner.next();: Reads the user's input from the console and stores it in the confirm variable.

if (confirm.equalsIgnoreCase("yes")) {
  • if (confirm.equalsIgnoreCase("yes")) {: This line checks if the user's confirmation input (stored in the confirm variable) is "yes", ignoring case sensitivity.
HashMap<String, String> personDetail = new HashMap<>();
System.out.println("Enter Name: ");
personDetail.put("Name", scanner.next());
System.out.println("Enter Gender: ");
personDetail.put("Gender", scanner.next());
System.out.println("Enter Age: ");
personDetail.put("Age", scanner.next());
System.out.println("Enter Phone number: ");
personDetail.put("Phone_No", scanner.next());
personDetail.put("Ticket_Price", Integer.toString(prizeOfTicket));
  • These lines prompt the user to enter their personal details and store them in a HashMap named personDetail:

    • HashMap<String, String> personDetail = new HashMap<>();: Initializes a new HashMap to store the user's details.

    • System.out.println("Enter Name: ");: Prompts the user to enter their name.

    • personDetail.put("Name", scanner.next());: Reads the user's input for their name using the Scanner object scanner and stores it in the personDetail HashMap with the key "Name".

    • System.out.println("Enter Gender: ");: Prompts the user to enter their gender.

    • personDetail.put("Gender", scanner.next());: Reads the user's input for their gender and stores it in the HashMap personDetail with the key "Gender".

    • System.out.println("Enter Age: ");: Prints a message prompting the user to enter their age.

    • personDetail.put("Age", scanner.next());: Reads the age entered by the user using the Scanner object scanner and stores it in the HashMap personDetail with the key "Age".

    • System.out.println("Enter Phone number: ");: Prints a message prompting the user to enter their phone number.

    • personDetail.put("Phone_No", scanner.next());: Reads the phone number entered by the user using the Scanner object scanner and stores it in the HashMap personDetail with the key "Phone_No".

    • personDetail.put("Ticket_Price", Integer.toString(prizeOfTicket));: Stores the ticket price (prizeOfTicket) in the HashMap personDetail with the key "Ticket_Price".

tableOfChart.get(Integer.toString(rowNumber - 1)).put(Integer.toString(columnNumber), "B");

This line updates the tableOfChart HashMap to mark the booked seat as "B" (booked). Here's what each part does:

  • tableOfChart.get(Integer.toString(rowNumber - 1)): Retrieves the HashMap corresponding to the specified row number (rowNumber - 1) from the tableOfChart HashMap. Since row numbers are 1-based but array indices are 0-based, we subtract 1 to get the correct index.

  • .put(Integer.toString(columnNumber), "B"): Inserts or updates the entry in the retrieved HashMap for the specified column number (columnNumber) with the value "B" to indicate that the seat is booked.

bookedSeat++;

This line increments the bookedSeat count by 1, indicating that a seat has been booked.

totalIncome += prizeOfTicket;

This line updates the totalIncome variable by adding the price of the booked ticket (prizeOfTicket). The prizeOfTicket variable holds the price of the ticket calculated based on various factors such as theater occupancy and seat location.

bookedTicketPerson[rowNumber - 1][columnNumber - 1] = personDetail.toString();

This line stores the details of the person booking the ticket in the bookedTicketPerson array at the specified rowNumber and columnNumber. Since array indices are 0-based, we subtract 1 from both rowNumber and columnNumber to get the correct indices. The personDetail.toString() converts the details stored in the personDetail HashMap to a string representation.

System.out.println("Booked Successfully");

This line prints a success message to confirm that the booking process was completed successfully.

} else {
    System.out.println("This seat is already booked by someone.");
}

This else block executes if the seat at the specified row and column number is already booked. It prints a message indicating that the seat is already booked.

} else {
    System.out.println("*** Invalid Input ***");
}

This else block executes if the entered row number or column number is not within the valid range of available seats. It prints a message indicating that the input is invalid.

Let's break down each line of the showBookedTicketUserInfo method:

System.out.println("Enter Row number: ");
int enterRow = scanner.nextInt();

This line prompts the user to enter the row number for which they want to see booking information and reads the input row number using the nextInt() method of the Scanner class. It assigns the entered row number to the variable enterRow.

System.out.println("Enter Column number: ");
int enterColumn = scanner.nextInt();

Similar to the previous line, this prompts the user to enter the column number for the booking information and reads the input column number using nextInt(). It assigns the entered column number to the variable enterColumn.

if (enterRow >= 1 && enterRow <= row && enterColumn >= 1 && enterColumn <= seats) {

This line checks if the entered row and column numbers are within the valid range of available seats. It ensures that both the row and column numbers are greater than or equal to 1 (since seat numbering typically starts from 1) and less than or equal to the total number of rows (row) and seats per row (seats), respectively.

if (tableOfChart.get(Integer.toString(enterRow - 1)).get(Integer.toString(enterColumn)).equals("B")) {

This line checks if the seat at the specified row and column is booked. It retrieves the value at the specified row and column from the tableOfChart HashMap. Since the row numbers are 1-based and array indices are 0-based, we subtract 1 from the entered row number (enterRow - 1). It then retrieves the value at the specified column using Integer.toString(enterColumn). If the retrieved value is "B", it indicates that the seat is booked.

String person = bookedTicketPerson[enterRow - 1][enterColumn - 1];
System.out.println(person);

If the seat is booked, this line retrieves the booking information (stored as a string) from the bookedTicketPerson array at the specified row and column. It then prints this information, which includes details of the person who booked the seat.

} else {
    System.out.println("---**---  Vacant seat  ---**---");
}

If the seat is not booked (i.e., the condition in the previous if statement is false), this line prints a message indicating that the seat is vacant.

} else {
    System.out.println("*** Invalid Input ***");
}

This else block executes if the entered row or column number is not within the valid range of available seats. It prints a message indicating that the input is invalid.

Sure, let's break down each line of the showAllBookedTicketUserInfo method:

for (int i = 0; i < row; i++) {

This line starts a loop that iterates through each row of the bookedTicketPerson array. It initializes the loop control variable i to 0 and continues looping as long as i is less than the total number of rows (row).

for (int j = 0; j < seats; j++) {

Within the outer loop, this line starts another loop that iterates through each seat in the current row. It initializes the loop control variable j to 0 and continues looping as long as j is less than the total number of seats per row (seats).

if (bookedTicketPerson[i][j] != null) {

This line checks if the element in the bookedTicketPerson array at the current row i and column j is not null. If it's not null, it means that a ticket is booked for this seat.

System.out.println("Seat (" + (i + 1) + ", " + (j + 1) + "): " + bookedTicketPerson[i][j]);

If a ticket is booked for the current seat, this line prints information about the booked ticket. It constructs a string that includes the seat coordinates (row and column numbers incremented by 1 to adjust for 0-based indexing) and the booking information stored in the bookedTicketPerson array at position [i][j].

Concluding our exploration of the Movie Ticket Booking System, we've delved into its Java implementation, dissecting each component from user authentication to ticket booking and information retrieval. Through this detailed analysis, we've gained insights into how such systems can be structured and programmed, addressing user needs while ensuring system integrity and efficiency.