Menu
CoddyTech

检查库存情况

本课属于 Coddy GDScript 学习旅程的“逻辑与流程”单元。第 74 课,共 78 课。

challenge icon

挑战

简单

添加命令 check。保留你在前面步骤中编写的所有内容。

在 _ready() 上方编写函数 check_availability(inventory, item)。它不打印任何内容,并且返回一个 int:

  • 如果物品在 inventory 中,返回该物品的库存数量
  • 如果找不到该物品,则返回 -1。库存数量永远不会是负数,因此 -1 只能表示 "not found"。

在循环中,遇到像 check Apple 这样的输入行时:

  • 如果输入恰好不包含 2 个部分,则打印 Error: Use check ITEM
  • 否则调用 check_availability(),如果返回 -1,则打印 Item not found;否则打印物品名称、: 、库存数量和 in stock

对于命令 add Apple 0.5 100、add Banana 0.2 50、update Apple -20、update Banana 30、check Apple、check Banana、check Orange 和 exit,输出为:

Inventory Management System
Item 'Apple' added successfully.
Item 'Banana' added successfully.
Stock for 'Apple' updated successfully.
Stock for 'Banana' updated successfully.
Apple: 80 in stock
Banana: 80 in stock
Item not found
Goodbye!

亲手试试

extends Node

func add_item(inventory: Dictionary, item: String, price: float, stock: int) -> void:
	if inventory.has(item):
		print("Error: Item '%s' already exists." % item)
		return
	inventory[item] = {"price": price, "stock": stock}
	print("Item '%s' added successfully." % item)

func update_stock(inventory: Dictionary, item: String, quantity: int) -> void:
	if not inventory.has(item):
		print("Error: Item '%s' not found." % item)
		return
	var new_stock: int = inventory[item]["stock"] + quantity
	if new_stock < 0:
		print("Error: Insufficient stock for '%s'." % item)
		return
	inventory[item]["stock"] = new_stock
	print("Stock for '%s' updated successfully." % item)

func _ready():
	# 库存字典:商品名称 -> {"price": float, "stock": int}
	var inventory := {}
	print("Inventory Management System")

	while true:
		var line := OS.read_string_from_stdin()
		var parts := line.split(" ")
		var command := parts[0]

		if command == "exit":
			print("Goodbye!")
			break
		elif command == "show":
			print(inventory)
		elif command == "add":
			if parts.size() != 4:
				print("Error: Use add ITEM PRICE STOCK")
			elif not parts[2].is_valid_float() or not parts[3].is_valid_int():
				print("Error: Price and stock must be numeric.")
			else:
				add_item(inventory, parts[1], float(parts[2]), int(parts[3]))
		elif command == "update":
			if parts.size() != 3:
				print("Error: Use update ITEM QUANTITY")
			elif not parts[2].is_valid_int():
				print("Error: Quantity must be an integer.")
			else:
				update_stock(inventory, parts[1], int(parts[2]))
		else:
			print("Unknown command")

逻辑与流程中的所有课

自己练习: GDScript 在线编译器