Skip to content
Java project #17Intermediate

Movie Ticket Booking

A cinema seat map with three seat classes, all-or-nothing bookings, best-available adjacent seat search, cancellations with fee retention and sales reports.

Estimated time
~4 hours to build
Files
4 files · 338 lines
Technologies
Java 21, 2D arrays, Enums with data, Records, LinkedHashMap

Introduction

Seat booking combines a 2D data structure (the hall), business rules (prices, fees, refunds) and a small search algorithm: finding the best block of adjacent free seats. It is a compact, realistic exercise in arrays, enums and careful validation.

Problem statement

Model a hall with rows A–H of 10 seats: rows A–B are recliners (₹450), C–E premium (₹280), F–H classic (₹180), plus a ₹30 convenience fee per ticket. Allow booking specific seats (all-or-nothing: reject the whole booking if any seat is taken, repeated or doesn't exist), booking the best block of N adjacent seats in a class, cancelling bookings (refunding everything except the fees), printing the seat map and a report of seats sold and takings per class.

Objectives

  • Represent a seating plan with a 2D array
  • Validate a whole request before changing anything
  • Implement a scored search for the best seat block
  • Use an enum with data for pricing

Features

  • Seat map with classes
  • Specific or best-available bookings
  • Cancellations with fee retention
  • Occupancy and revenue per class

Concepts demonstrated

  • 2D arrays
  • All-or-nothing operations
  • Search with scoring
  • Input parsing
  • Reporting

System architecture

seatOwner[row][col] holds the customer's name or null. parseSeat converts text like E7 into indexes and validates it. confirm checks every requested seat first and only then marks them and creates a Booking record. bestBlock slides a window of N seats along each row of the class, scoring blocks by their distance from the centre of the row plus a small penalty for rows further back in the class, and keeps the lowest score. SeatClass maps rows to classes and prices.

Folder structure

TextProject tree
movie-ticket-booking/
├── README.md
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

165 lines
Javasrc/Main.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
/**
* Movie Ticket Booking — a cinema seat map with three seat classes (enum), booking specific
* seats or the best available block of adjacent seats, cancellations, a convenience fee,
* occupancy and revenue reports.
*
* Commands:
* map book NAME SEAT... best NAME CLASS COUNT cancel BOOKING_ID report quit
* Seats are written as row letter + number, e.g. A1, E7.
*/
public class Main {
enum SeatClass {
RECLINER(450, "AB"), PREMIUM(280, "CDE"), CLASSIC(180, "FGH");
final int price;
final String rows;
SeatClass(int price, String rows) { this.price = price; this.rows = rows; }
static SeatClass ofRow(char row) {
for (SeatClass c : values()) if (c.rows.indexOf(row) >= 0) return c;
throw new IllegalArgumentException("no row " + row);
}
}
record Booking(int id, String customer, List<String> seats, int amount) { }
static final int SEATS_PER_ROW = 10;
static final String ROWS = "ABCDEFGH";
static final int FEE_PER_TICKET = 30;
static final String[][] seatOwner = new String[ROWS.length()][SEATS_PER_ROW]; // null = free
static final Map<Integer, Booking> bookings = new LinkedHashMap<>();
static int nextId = 1;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("=== Cinema Booking: 'Java: The Movie', 7:30 PM ===");
while (true) {
System.out.print("> ");
if (!in.hasNextLine()) break;
String[] p = in.nextLine().trim().split("\\s+");
System.out.println();
try {
switch (p[0].toLowerCase()) {
case "map" -> printMap();
case "book" -> {
if (p.length < 3) throw new IllegalArgumentException("usage: book NAME SEAT...");
List<int[]> seats = new ArrayList<>();
for (int i = 2; i < p.length; i++) seats.add(parseSeat(p[i]));
confirm(p[1], seats);
}
case "best" -> {
SeatClass c = seatClass(p[2]);
int count = Integer.parseInt(p[3]);
if (count < 1 || count > SEATS_PER_ROW) throw new IllegalArgumentException("count must be 1-" + SEATS_PER_ROW);
List<int[]> block = bestBlock(c, count);
if (block == null) throw new IllegalStateException("no " + count + " adjacent " + c + " seats left");
confirm(p[1], block);
}
case "cancel" -> {
Booking b = bookings.remove(Integer.parseInt(p[1]));
if (b == null) throw new IllegalArgumentException("no booking #" + p[1]);
for (String s : b.seats()) {
int[] rc = parseSeat(s);
seatOwner[rc[0]][rc[1]] = null;
}
System.out.println("Cancelled #" + b.id() + " for " + b.customer() + ": " + b.seats() + ", refund Rs " + (b.amount() - FEE_PER_TICKET * b.seats().size()) + " (fee kept)");
}
case "report" -> report();
case "quit" -> { return; }
default -> System.out.println("Commands: map book best cancel report quit");
}
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
System.out.println("Error: missing or invalid arguments");
} catch (IllegalArgumentException | IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
static SeatClass seatClass(String s) {
for (SeatClass c : SeatClass.values()) if (c.name().equalsIgnoreCase(s)) return c;
throw new IllegalArgumentException("seat classes are recliner, premium and classic");
}
static int[] parseSeat(String s) {
s = s.toUpperCase();
if (!s.matches("[A-Z]\\d{1,2}")) throw new IllegalArgumentException("invalid seat " + s);
int row = ROWS.indexOf(s.charAt(0)), col = Integer.parseInt(s.substring(1)) - 1;
if (row < 0 || col < 0 || col >= SEATS_PER_ROW) throw new IllegalArgumentException("seat " + s + " doesn't exist");
return new int[]{row, col};
}
static String name(int[] rc) { return "" + ROWS.charAt(rc[0]) + (rc[1] + 1); }
// All-or-nothing: if any requested seat is taken (or repeated), nothing is booked.
static void confirm(String customer, List<int[]> seats) {
List<String> names = new ArrayList<>();
for (int[] rc : seats) {
String n = name(rc);
if (seatOwner[rc[0]][rc[1]] != null) throw new IllegalStateException("seat " + n + " is already booked");
if (names.contains(n)) throw new IllegalArgumentException("seat " + n + " listed twice");
names.add(n);
}
int amount = 0;
for (int[] rc : seats) {
seatOwner[rc[0]][rc[1]] = customer;
amount += SeatClass.ofRow(ROWS.charAt(rc[0])).price + FEE_PER_TICKET;
}
Booking b = new Booking(nextId++, customer, names, amount);
bookings.put(b.id(), b);
System.out.println("Booking #" + b.id() + " for " + customer + ": " + names + " total Rs " + amount + " (incl. Rs " + FEE_PER_TICKET + "/ticket fee)");
}
// Prefers rows nearer the middle of the class and seats nearer the centre of the row.
static List<int[]> bestBlock(SeatClass c, int count) {
List<int[]> best = null;
double bestScore = Double.MAX_VALUE;
for (char rowChar : c.rows.toCharArray()) {
int r = ROWS.indexOf(rowChar);
for (int start = 0; start + count <= SEATS_PER_ROW; start++) {
boolean free = true;
for (int k = start; k < start + count; k++) free &= seatOwner[r][k] == null;
if (!free) continue;
double centre = start + (count - 1) / 2.0;
double score = Math.abs(centre - (SEATS_PER_ROW - 1) / 2.0) + 0.5 * c.rows.indexOf(rowChar);
if (score < bestScore) {
bestScore = score;
best = new ArrayList<>();
for (int k = start; k < start + count; k++) best.add(new int[]{r, k});
}
}
}
return best;
}
static void printMap() {
System.out.println(" SCREEN THIS WAY");
System.out.print(" ");
for (int c = 1; c <= SEATS_PER_ROW; c++) System.out.printf("%-3d", c);
System.out.println();
for (int r = 0; r < ROWS.length(); r++) {
StringBuilder sb = new StringBuilder(" " + ROWS.charAt(r) + " ");
for (int c = 0; c < SEATS_PER_ROW; c++) sb.append(seatOwner[r][c] == null ? "[ ]" : "[X]");
sb.append(" ").append(SeatClass.ofRow(ROWS.charAt(r)));
System.out.println(sb);
}
}
static void report() {
for (SeatClass c : SeatClass.values()) {
int total = c.rows.length() * SEATS_PER_ROW, sold = 0;
for (char row : c.rows.toCharArray())
for (String owner : seatOwner[ROWS.indexOf(row)]) if (owner != null) sold++;
System.out.printf(" %-9s %2d/%d sold (%3.0f%%) ticket revenue Rs %,d%n", c, sold, total, 100.0 * sold / total, sold * c.price);
}
int revenue = bookings.values().stream().mapToInt(Booking::amount).sum();
System.out.printf(" %d active booking(s), takings including fees Rs %,d%n", bookings.size(), revenue);
}
}

What each file does

src/Main.java
Seat classes, the seat map, all-or-nothing booking, the best-block search, cancellation and reports.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Cinema Booking: 'Java: The Movie', 7:30 PM ===
>
Booking #1 for Asha: [E5, E6] total Rs 620 (incl. Rs 30/ticket fee)
>
Error: seat E6 is already booked
>
Error: seat E7 listed twice
>
Error: seat Z1 doesn't exist
>
Error: seat A11 doesn't exist
>
Booking #2 for Meera: [C4, C5, C6, C7] total Rs 1240 (incl. Rs 30/ticket fee)
>
Booking #3 for Kiran: [A5, A6] total Rs 960 (incl. Rs 30/ticket fee)
>
Booking #4 for Team: [F1, F2, F3, F4, F5, F6, F7, F8, F9, F10] total Rs 2100 (incl. Rs 30/ticket fee)
>
Booking #5 for Team2: [G1, G2, G3, G4, G5, G6, G7, G8, G9, G10] total Rs 2100 (incl. Rs 30/ticket fee)
>
Error: seat classes are recliner, premium and classic
>
Cancelled #2 for Meera: [C4, C5, C6, C7], refund Rs 1120 (fee kept)
>
Error: no booking #9
>
Booking #6 for John: [C4, C5, C6, C7] total Rs 1240 (incl. Rs 30/ticket fee)
>
SCREEN THIS WAY
1 2 3 4 5 6 7 8 9 10
A [ ][ ][ ][ ][X][X][ ][ ][ ][ ] RECLINER
B [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] RECLINER
C [ ][ ][ ][X][X][X][X][ ][ ][ ] PREMIUM
D [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] PREMIUM
E [ ][ ][ ][ ][X][X][ ][ ][ ][ ] PREMIUM
F [X][X][X][X][X][X][X][X][X][X] CLASSIC
G [X][X][X][X][X][X][X][X][X][X] CLASSIC
H [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] CLASSIC
>
RECLINER 2/20 sold ( 10%) ticket revenue Rs 900
PREMIUM 6/30 sold ( 20%) ticket revenue Rs 1,680
CLASSIC 20/30 sold ( 67%) ticket revenue Rs 3,600
5 active booking(s), takings including fees Rs 7,020
>
Input
book Asha E5 E6
book Ravi E6 E7
book Ravi E7 E7
book Ravi Z1
book Ravi A11
best Meera premium 4
best Kiran recliner 2
best Team classic 10
best Team2 classic 10
best Lina gold 2
cancel 2
cancel 9
best John premium 4
map
report
quit

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • Ravi's request for E6 and E7 is refused entirely because E6 is taken; E7 is not booked either.
  • The best 4 premium seats are C4–C7, the centre of the front premium row.
  • Cancelling Meera's booking refunds ₹1,120 (her ₹120 in fees is kept), and John then gets the same seats.

Common errors

Half of a group booking succeeds

Validate all seats before marking any of them.

ArrayIndexOutOfBoundsException for seat A11

Check the column against SEATS_PER_ROW when parsing.

Possible improvements

  • Several shows and screens
  • Seat holds that expire after five minutes
  • Discount codes and loyalty points

Additional challenges

  1. 1Allow a group to be split across two adjacent rows if no single block fits.
  2. 2Keep wheelchair spaces that can only be booked with a flag.
  3. 3Print the map showing who booked each seat.

Built and tested it yourself? Mark it to update your dashboard.