Write a Theatre class that holds a 2D seat map, books seats like "B3", refuses invalid or taken seats, and prints the seat map and occupancy.
Solution
Main.java
class Theatre {
private final boolean[][] taken;
Theatre(int rows, int cols) { taken = new boolean[rows][cols]; }
String book(String seat) {
int r = Character.toUpperCase(seat.charAt(0)) - 'A';
int c = Integer.parseInt(seat.substring(1)) - 1;
if (r < 0 || r >= taken.length || c < 0 || c >= taken[0].length) return seat + ": no such seat";
if (taken[r][c]) return seat + ": already booked";
taken[r][c] = true;
return seat + ": booked";
}
void print() {
int count = 0;
for (int r = 0; r < taken.length; r++) {
StringBuilder sb = new StringBuilder().append((char) ('A' + r)).append(' ');
for (boolean t : taken[r]) { sb.append(t ? 'X' : '.'); if (t) count++; }
System.out.println(sb);
}
System.out.printf("%d of %d seats booked%n", count, taken.length * taken[0].length);
}
}
public class Main {
public static void main(String[] args) {
Theatre t = new Theatre(3, 6);
for (String s : new String[]{"A1", "B3", "b4", "B3", "D1", "C7", "C6"}) System.out.println(t.book(s));
t.print();
}
}
Output Verified by compiling and running
A1: booked
B3: booked
b4: booked
B3: already booked
D1: no such seat
C7: no such seat
C6: booked
A X.....
B ..XX..
C .....X
4 of 18 seats booked
The seat array is private: callers can only book through the method, which validates every request.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!