Loading...
Loading...
A bus has n seats numbered 1 to n, all free at the start. The booking desk gets q commands, each BOOK k or CANCEL k. Keep the seats in a boolean[].
For each command print one line:
Seat k booked or Seat k cancelled when it works,Error: unknown command if the line is not exactly two words or the first word is not BOOK or CANCEL (capital letters only),Error: seat number must be a whole number if k is not a whole number,Error: no seat k if k is not between 1 and n (catch the ArrayIndexOutOfBoundsException),Error: seat k is already booked or Error: seat k is not booked, thrown as an IllegalArgumentException by your book and cancel methods.At the end print Booked seats: followed by the booked seat numbers in order, or Booked seats: none.
Booked seats: line.int and has no plus signExample 1
Input
5 6 BOOK 2 BOOK 5 BOOK 2 CANCEL 3 BOOK 6 CANCEL 2
Output
Seat 2 booked Seat 5 booked Error: seat 2 is already booked Error: seat 3 is not booked Error: no seat 6 Seat 2 cancelled Booked seats: 5
Example 2
Input
3 3 book 1 BOOK one RESERVE 2
Output
Error: unknown command Error: seat number must be a whole number Error: unknown command Booked seats: none
Commands are case-sensitive.
Try the problem first. Open one hint at a time.
Write book(seats, k) and cancel(seats, k): each reads seats[k - 1], which throws for a seat outside the bus, and throws IllegalArgumentException for the wrong state.
In the loop, split the line, throw IllegalArgumentException("unknown command") for a bad command word, then parse k.
Catch NumberFormatException and ArrayIndexOutOfBoundsException before IllegalArgumentException.
Build the final line with a loop over the seats, adding " " + seatNumber for each booked seat.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor