Loading...
Loading...
Java · References, Casting & Immutability
A student wallet keeps its balance as an immutable Rupees object. Its constructor throws IllegalArgumentException for a negative amount, and plus and minus return new objects. Apply each operation in order. A spend that would take the balance below zero is refused, and the balance stays as it was.
ADD x or SPEND x.Refused <x> for every refused spend, at the moment it happens, then Balance <final balance>.Example
Input
500 4 SPEND 200 SPEND 400 ADD 1000 SPEND 400
Output
Refused 400 Balance 900
500 − 200 = 300; 400 is more than 300, so it is refused; then 300 + 1000 − 400 = 900.
Try the problem first. Open one hint at a time.
Put the amount < 0 check in the constructor; then minus only needs return new Rupees(amount - x);.
Wrap balance = balance.minus(x); in try/catch. If the constructor throws, the assignment never happens, so balance keeps the old object.
Use long: the balance can pass 2 147 483 647.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor