Menu
CoddyTech

Kiểm tra tình trạng còn hàng

Thuộc phần Logic và luồng chương trình trong hành trình GDScript của Coddy. Bài học 74 trên 78.

challenge icon

Thử thách

Dễ

Thêm lệnh check. Giữ lại mọi thứ bạn đã viết ở các bước trước.

Viết hàm check_availability(inventory, item) phía trên _ready(). Hàm này không in gì và trả về một int:

  • số lượng tồn kho của mặt hàng nếu mặt hàng có trong inventory
  • -1 nếu không tìm thấy mặt hàng. Số lượng tồn kho không bao giờ âm, vì vậy -1 chỉ có thể mang nghĩa "not found".

Trong vòng lặp, với một dòng như check Apple:

  • in ra Error: Use check ITEM nếu dòng đó không có chính xác 2 phần
  • nếu không, gọi check_availability() và in ra Item not found nếu giá trị trả về là -1, hoặc tên mặt hàng, : , số lượng tồn kho và in stock

Với các lệnh add Apple 0.5 100, add Banana 0.2 50, update Apple -20, update Banana 30, check Apple, check Banana, check Orange và exit, đầu ra là:

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!

Tự làm thử

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():
	# Từ điển hàng tồn kho: tên mặt hàng -> {"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")

Tất cả bài học trong Logic và luồng chương trình

Tự luyện tập: Trình biên dịch GDScript online