You build the class Event. An event has a name and a number of free seats.
Implement the class Event:
Event(name, seats)creates an event withseatsfree seats.nameis a field that any code can read.- The seats left are a private field, as in the Access Modifiers lesson.
book(n)booksnseats and returns how many are left.
A booking can fail. Then book raises an error with a message, and nothing changes.
- When
nis 0 or less, the message is"invalid number". - When
nis more than the seats left, the message is"sold out".
Raise the errors the way the Errors and Exceptions lesson does:
- Python:
raise ValueError("sold out"). - JavaScript and TypeScript:
throw new Error("sold out"). - Java, Kotlin and Scala: throw an
IllegalArgumentException. - C#: throw an
ArgumentException. The method is namedBook. - C++: throw an
invalid_argument. - Swift: throw a
BookingError. The starter code declares it.
The input lists the bookings of each event, in order. The tests call book and catch its errors. For each event they print its name. Then they print one line per booking:
booked 2, 3 leftwhen 2 seats were booked and 3 are left.error: sold outwhen the booking failed with the message"sold out".
Example 1:
Input:
Event("Concert", 5)
book(2)
book(4)
book(3)
Output:
Concert
booked 2, 3 left
error: sold out
booked 3, 0 left
Explanation:
2 seats are booked, so 3 are left.
4 is more than 3, so the error is "sold out".
The failed booking changed nothing.
So book(3) gets the last 3 seats.
Example 2:
Input:
Event("Play", 4)
book(-1)
book(4)
Output:
Play
error: invalid number
booked 4, 0 left
Explanation:
No one can book -1 seats.
book(4) then takes all 4 seats.
Example 3:
Input:
Event("Match", 0)
book(0)
Output:
Match
error: invalid number
Explanation:
The event has no seats at all.
Booking 0 seats is never valid, so the error is "invalid number".
Constraints:
- Each event has 0 to 100,000 seats.
- Each
nis a whole number from -100 to 100,000. - An event gets 1 to 1,000 bookings.
- Event names are one word of English letters.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
