Menu
CoddyTech

재고 확인

Coddy GDScript 여정의 논리와 흐름 섹션에 포함된 레슨. 78개 중 74번째.

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():
	# inventory: 항목 이름 -> {"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 컴파일러