은행 원장
Coddy R 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 57번째.
챌린지
어려움네 개의 파일에서 Reference Classes를 사용해 작은 은행을 만드세요. 모든 정의는 suppressMessages()로 감싸며, 모든 stop()에서 call. = FALSE를 사용하세요.
Account.R:id,owner,balance필드(시작 시 0).deposit(x)와withdraw(x)는x가 누락되었거나 1보다 작을 때invalid amount와 함께 중단합니다. 잔액이lowest()보다 작아지게 될 경우withdraw()는insufficient funds in 2와 함께 중단하며,lowest()는 0입니다.month_end()는 아무 작업도 하지 않고,line()은kind()를 사용해1 ada checking: -20을 반환합니다.Checking.R: 종류는checking이며 잔액은 -100까지 내려갈 수 있습니다.Savings.R: 종류는savings이며, 월별 출금은 최대 2회입니다(withdrawal limit on 2). 성공한 경우에만 횟수를 셉니다.month_end()는 1%의 이자를 더하고 내림한 뒤 횟수를 초기화합니다.Bank.R:open_account(kind, id, owner)(account 2 exists),get_account(id)(no account 9), 출금이 실패하면 아무것도 변경하지 않는transfer(from, to, amount), 모든 계정에 대한month_end(), 그리고 id순으로 정렬된 모든 계정의 줄을 반환하는statement()을 구현합니다.
제공된 코드는 open checking 1 ada, dep 1 100, wd 2 30, tr 1 2 50 또는 month 명령을 읽고, 각 명령에 대해 ok 또는 오류 메시지를 출력한 다음 statement를 출력합니다.
코드는 Account.R, Checking.R, Savings.R 및 Bank.R에 작성합니다. main.R에는 제공된 입력/출력 코드가 들어 있으며 편집할 수 없습니다.
직접 해보기
source("Account.R")
source("Checking.R")
source("Savings.R")
source("Bank.R")
# 제공된 입력/출력 코드: 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
bank <- Bank$new()
for (line in input) {
p <- strsplit(line, " ")[[1]]
n <- suppressWarnings(as.numeric(p[-1]))
msg <- tryCatch({
switch(p[1],
open = bank$open_account(p[2], as.numeric(p[3]), p[4]),
dep = bank$get_account(n[1])$deposit(n[2]),
wd = bank$get_account(n[1])$withdraw(n[2]),
tr = bank$transfer(n[1], n[2], n[3]),
month = bank$month_end())
"ok"
}, error = function(e) conditionMessage(e))
cat(line, ": ", msg, "\n", sep = "")
}
for (l in bank$statement()) cat(l, "\n", sep = "")
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 R 컴파일러