Menu
CoddyTech

Cập nhật hàng tồn kho

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 73 trên 78.

challenge icon

Thử thách

Dễ

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

Dòng lệnh như update Apple -20 cộng -20 vào số lượng tồn kho của Apple: số lượng dương nghĩa là nhập hàng, số lượng âm nghĩa là lấy hàng ra.

Viết hàm update_stock(inventory, item, quantity) phía trên _ready():

  1. Nếu mặt hàng không có trong inventory, in ra Error: Item 'Orange' not found. (kèm tên mặt hàng)
  2. Nếu số lượng tồn kho mới sẽ là số âm, in ra Error: Insufficient stock for 'Apple'. và giữ nguyên số lượng tồn kho cũ
  3. Nếu không, lưu số lượng tồn kho mới và in ra Stock for 'Apple' updated successfully.

Trong vòng lặp, thêm nhánh elif cho lệnh update:

  • Nếu dòng lệnh không có đúng 3 phần, in ra Error: Use update ITEM QUANTITY
  • Nếu số lượng không phải là số nguyên, in ra Error: Quantity must be an integer.
  • Nếu không, gọi update_stock()

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

Inventory Management System
Item 'Apple' added successfully.
Item 'Banana' added successfully.
Error: Item 'Apple' already exists.
Stock for 'Apple' updated successfully.
Stock for 'Banana' updated successfully.
Error: Item 'Orange' not found.
Error: Insufficient stock for 'Apple'.
{ "Apple": { "price": 0.5, "stock": 80 }, "Banana": { "price": 0.2, "stock": 80 } }
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 _ready():
	# Từ điển inventory: 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]))
		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