은행 원장
Coddy Kotlin 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 57번째.
챌린지
어려움작은 은행을 만드세요.
BankError(message)는Exception을 확장하는 봉인 클래스이며, 하위 클래스는InvalidAmount(invalid amount),Insufficient(id)(insufficient funds in 2),WithdrawalLimit(id)(withdrawal limit on 2) 및NoAccount(id)(no account 9)입니다.Account(id, owner)는 추상 클래스입니다. 해당balance는 어디서나 읽을 수 있지만 계정 클래스만 변경할 수 있습니다.deposit(amount)와withdraw(amount)는 1보다 작은 금액에 대해InvalidAmount를 발생시키며,withdraw는 잔액이 계정의lowestBalance아래로 내려가게 되면Insufficient를 발생시킵니다. 추상kind와 아무 작업도 하지 않는 openmonthEnd()를 선언합니다.Checking은 -100까지 초과 인출을 허용합니다.Savings는 0 아래로 내려가지 않으며, 한 달에 최대 2회의 인출만 허용하고(WithdrawalLimit),monthEnd()에서 1%의 이자를 내림하여 더한 다음 인출 횟수를 초기화합니다.Bank에는open(kind, id, owner),account(id)(NoAccount를 발생시킴), 두 계정을 먼저 조회한 후 인출하고 입금하는transfer(from, to, amount), 모든 계정에 대해 실행하는monthEnd(), 그리고 id순으로 정렬된accounts()가 있습니다.
제공된 코드는 open checking 1 ada, open savings 2 bo, dep 1 100, wd 2 30, tr 1 2 50 또는 month 명령을 읽고, ok 또는 오류 메시지를 출력한 다음, 마지막으로 모든 계정을 1 ada checking: -20과 같은 형식으로 출력합니다.
코드는 BankError.kt, InvalidAmount.kt, Insufficient.kt, WithdrawalLimit.kt, NoAccount.kt, Account.kt, Checking.kt, Savings.kt 및 Bank.kt에 작성합니다. Main.kt에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.
직접 해보기
fun main() {
// 제공된 입력/출력 코드: 그대로 유지하세요
val input = generateSequence(::readLine).toList()
val bank = Bank()
for (cmd in input) {
val p = cmd.split(" ")
try {
when (p[0]) {
"open" -> bank.open(p[1], p[2].toInt(), p[3])
"dep" -> bank.account(p[1].toInt()).deposit(p[2].toInt())
"wd" -> bank.account(p[1].toInt()).withdraw(p[2].toInt())
"tr" -> bank.transfer(p[1].toInt(), p[2].toInt(), p[3].toInt())
else -> bank.monthEnd()
}
println("ok")
} catch (e: BankError) {
println(e.message)
}
}
for (a in bank.accounts()) println("${a.id} ${a.owner} ${a.kind}: ${a.balance}")
}
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: Kotlin 플레이그라운드