Menu
Coddy logo textTech

残高の取得

CoddyのLuaジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 22/70。

challenge icon

チャレンジ

簡単

あなたの Digital Bank は本格的に形になってきました!Account は deposit を受け取り、適切な funds のチェックを行いながら withdrawal を処理できます。次は balance を取得する getter method を追加し、その後、現実的な銀行のシナリオですべてを組み合わせましょう。

引き続き、既存のファイルを構築していきます。

  • Account.lua: 現在の balance を返す :getBalance() method を追加します。これは先ほど学んだ getter pattern に従うもので、field に直接アクセスするのではなく、内部データへの制御されたアクセスを提供します。既存のすべての機能(constructor、deposit、withdraw method)を維持してください。
  • main.lua: account を作成し、一連の銀行操作を実行して、実際のシナリオで deposit、withdrawal、balance のチェックがどのように連携するかを示します。

5 つの入力を受け取ります。

  1. Initial deposit amount
  2. First withdrawal amount
  3. Second deposit amount
  4. Second withdrawal amount
  5. Third withdrawal amount

main file で account を作成し、次の操作を順番に実行します。

  1. initial amount を Deposit し、:getBalance() を使用して balance を print する
  2. first amount を Withdraw し、その後 balance を print する
  3. second amount を Deposit し、その後 balance を print する
  4. second amount を Withdraw し、その後 balance を print する
  5. third withdrawal を Attempt し、その後 balance を print する

withdrawal に失敗した場合は、balance を print する前に Insufficient funds が print されることを忘れないでください。

たとえば、入力が 20050100180100 の場合、出力は次のようになります。

200
150
250
70
Insufficient funds
70

account は 200 から開始し、first withdrawal の後に 150 まで減少し、さらに deposit した後に 250 まで増加します。その後 180 を withdrawal すると 70 まで減少し、最後の 100 の withdrawal は funds 不足により失敗するため、70 のままになります。

自分で試してみよう

-- Accountモジュールを読み込む
local Account = require('Account')

-- 5つの入力を読み取る
local initialDeposit = tonumber(io.read())
local withdrawal1 = tonumber(io.read())
local deposit2 = tonumber(io.read())
local withdrawal2 = tonumber(io.read())
local withdrawal3 = tonumber(io.read())

-- アカウントを1つ作成する
local account = Account:new()

-- 初期金額を預け入れ、:getBalance()を使って残高を出力する
account:deposit(initialDeposit)
print(account:getBalance())

-- 最初の引き出しを試み、残高を出力する
account:withdraw(withdrawal1)
print(account:getBalance())

-- 2回目の金額を預け入れ、残高を出力する
account:deposit(deposit2)
print(account:getBalance())

-- 2回目の引き出しを試み、残高を出力する
account:withdraw(withdrawal2)
print(account:getBalance())

-- 3回目の引き出しを試み、残高を出力する
account:withdraw(withdrawal3)
print(account:getBalance())

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: Luaオンラインコンパイラ