Menu
CoddyTech

Xử lý lỗi

Thuộc phần Kiến thức nền tảng trong hành trình GDScript của Coddy. Bài học 89 trên 92.

challenge icon

Thử thách

Dễ

Cuối cùng, xử lý mọi lựa chọn không nằm trong khoảng từ 1 đến 5. Giữ lại mọi thứ bạn đã viết ở các bước trước và in ra:

Invalid choice. Please try again.

Sau thông báo này, vòng lặp đọc lựa chọn tiếp theo như trước.

Tự làm thử

extends Node

func _ready():
	print("Welcome to the Daily Expense Tracker!")

	# Hiển thị menu một lần
	print("\nMenu:")
	print("1. Add a new expense")
	print("2. View all expenses")
	print("3. Calculate total and average expense")
	print("4. Clear all expenses")
	print("5. Exit")

	# Mảng (array) rỗng để lưu các khoản chi
	var expenses: Array[float] = []

	while true:
		# Lấy lựa chọn của người dùng
		var choice := OS.read_string_from_stdin()

		if choice == "1":
			# Thêm khoản chi mới
			var amount := float(OS.read_string_from_stdin())
			expenses.append(amount)
			print("Expense added successfully!")
		elif choice == "2":
			# Xem tất cả khoản chi
			if expenses.is_empty():
				print("No expenses recorded yet.")
			else:
				print("Your expenses:")
				for i in range(expenses.size()):
					print(i + 1, ". ", expenses[i])
		elif choice == "3":
			# Tính tổng và trung bình các khoản chi
			if expenses.is_empty():
				print("No expenses recorded yet.")
			else:
				var total := 0.0
				for expense in expenses:
					total += expense
				var average := total / expenses.size()
				print("Total expense: ", total)
				print("Average expense: ", average)
		elif choice == "4":
			# Xóa tất cả khoản chi
			expenses.clear()
			print("All expenses cleared.")
		elif choice == "5":
			# Thoát chương trình
			print("Exiting the Daily Expense Tracker. Goodbye!")
			break

Tất cả bài học trong Kiến thức nền tảng

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