잔액 조회
Coddy Lua 여정의 객체 지향 프로그래밍 (Object Oriented Programming) 섹션에 포함된 레슨. 70개 중 22번째.
챌린지
쉬움디지털 은행이 정말 모습을 갖춰 가고 있습니다! 계좌가 입금을 받고 적절한 자금 확인을 통해 출금을 처리할 수 있게 되었습니다. 이제 잔액을 가져오는 getter method를 추가한 다음, 현실적인 은행 시나리오에서 모든 기능을 함께 사용해 보겠습니다.
기존 파일을 계속 확장합니다:
Account.lua: current balance를 반환하는:getBalance()method를 추가합니다. 이는 앞에서 배운 getter pattern을 따릅니다. 즉, 필드에 직접 접근하는 대신 내부 데이터에 대한 제어된 접근을 제공합니다. 기존의 모든 기능(constructor, deposit, withdraw methods)을 유지하세요.main.lua: account를 만들고 일련의 은행 작업을 실행하여 실제 상황에서 deposit, withdrawal, balance 확인이 어떻게 함께 작동하는지 보여 주세요.
다섯 개의 입력을 받습니다:
- initial deposit amount
- first withdrawal amount
- second deposit amount
- second withdrawal amount
- third withdrawal amount
main 파일에서 account를 만들고 다음 작업을 순서대로 수행하세요:
- initial amount를 Deposit한 다음
:getBalance()를 사용하여 잔액을 print합니다. - first amount를 Withdraw한 다음 잔액을 print합니다.
- second amount를 Deposit한 다음 잔액을 print합니다.
- second amount를 Withdraw한 다음 잔액을 print합니다.
- third withdrawal을 Attempt한 다음 잔액을 print합니다.
withdrawal이 실패하면 잔액을 print하기 전에 Insufficient funds가 출력된다는 점을 기억하세요.
예를 들어 입력이 200, 50, 100, 180, 100이면 출력은 다음과 같아야 합니다:
200
150
250
70
Insufficient funds
70account는 200에서 시작하여 first withdrawal 후 150으로 줄어들고, 또 한 번의 deposit 후 250으로 늘어납니다. 180을 withdraw한 후에는 70으로 줄어들며, 자금 부족으로 마지막 100 withdrawal이 실패하면 70으로 유지됩니다.
REQUIRED OUTPUT FORMAT:직접 해보기
-- Account 모듈을 불러온다
local Account = require('Account')
-- 다섯 개의 입력을 읽는다
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())
-- 단일 계정을 생성한다
local account = Account:new()
-- 초기 금액을 입금하고 :getBalance()를 사용하여 잔액을 출력한다
account:deposit(initialDeposit)
print(account:getBalance())
-- 첫 번째 출금을 시도하고 잔액을 출력한다
account:withdraw(withdrawal1)
print(account:getBalance())
-- 두 번째 금액을 입금하고 잔액을 출력한다
account:deposit(deposit2)
print(account:getBalance())
-- 두 번째 출금을 시도하고 잔액을 출력한다
account:withdraw(withdrawal2)
print(account:getBalance())
-- 세 번째 출금을 시도하고 잔액을 출력한다
account:withdraw(withdrawal3)
print(account:getBalance())
객체 지향 프로그래밍 (Object Oriented Programming)의 모든 레슨
직접 연습해 보세요: 온라인 Lua 컴파일러