#C14565. Inventory Management System
Inventory Management System
Inventory Management System
You are required to implement a basic inventory management system for a small role-playing game (RPG). The system supports three operations:
add <item> <quantity>
: Adds the specified quantity of the item to the inventory. If the quantity is negative, the program must outputValueError
and terminate.remove <item> <quantity>
: Removes the specified quantity from an existing item in the inventory. If the item does not exist, or if the quantity is negative or more than the available quantity, the program must outputKeyError
orValueError
respectively, and terminate immediately without processing further commands.view
: Outputs the current inventory in JSON format. The inventory should be displayed as a JSON object with keys in lexicographical order. For example, if the inventory contains a "sword" with quantity 2 and a "shield" with quantity 1, the output should be{"shield":1,"sword":2}
.
The input is provided via standard input and each operation is given on a new line. If an error occurs at any point, the program should output the corresponding error message and exit immediately.
Note: You must adhere to the input and output format exactly. Use LaTeX notation for any formulas if needed. (No formulas are required for this problem.)
inputFormat
The input is read from standard input. The first line contains an integer n
which indicates the number of operations. The following n
lines each contain a command in one of the following formats:
add <item> <quantity>
remove <item> <quantity>
view
The program should process the commands in the order given. It is guaranteed that the last command will be view
if no error occurs earlier.
outputFormat
After processing the commands, the program should output the inventory’s current state as a JSON object (without any extra spaces) to standard output. The keys in the JSON object must be sorted in lexicographical order. If an error occurs during any operation, output the corresponding error message (ValueError
or KeyError
) and do not process further commands.
3
add sword 2
add shield 1
view
{"shield":1,"sword":2}