Menu
CoddyTech

支出を追加する

CoddyのSwiftジャーニー「基礎」セクションの一部。レッスン 79/86。

challenge icon

チャレンジ

簡単

前のレッスンでは、ユーザーが"5"を入力すると終了するメニューループを作成しました。次に、オプション"1"の「Add expense」機能を実装しましょう。

オプション"1"を処理するようにコードを変更しましょう。

  1. ユーザーが"1"を入力したら、Enter expense amount:を表示します
  2. readLine()を使って支出額を読み取ります
  3. 入力をDoubleに変換し、expenses配列に追加します
  4. 支出額を正常に追加した後、Expense added!を表示します
  5. オプション"2"、"3"、"4"では引き続きComing soon...を表示します
  6. オプション"5"では引き続きGoodbye!を表示して終了します

期待される動作:

  • "1"が入力されたら、支出額の入力を促し、配列に追加して、確認メッセージを表示します
  • "5"が入力されるまで、各操作の後もメニューが表示され続けます

実行例:

1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
25.50
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
10.00
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
5
Goodbye!

自分で試してみよう

// Daily Expense Tracker - Menu Display

var expenses: [Double] = []

while true {
    // TODO: Write your code below to print the menu options
    // Each option should be on its own line with the format: "number. option text"
    print("1. Add expense")
    print("2. View all expenses")
    print("3. Show total and average")
    print("4. Clear all expenses")
    print("5. Exit")
    
    let choice = readLine()
    
    if choice == "5" {
        print("Goodbye!")
        break
    } else {
        print("Coming soon...")
    }
}

基礎のすべてのレッスン

自分で練習してみよう: Swiftプレイグラウンド