Menu
CoddyTech

回顾:银行账户

本课属于 Coddy Kotlin 学习旅程的“面向对象编程”单元。第 11 课,共 57 课。

challenge icon

挑战

中等

完成类 BankAccount(val owner: String, opening: Int)。它的 init 块要求 owner 非空白(owner is empty),并且开户存款不能为负数(opening must not be negative)。balance 有一个私有 setter。交易记录保存在一个私有的 MutableList 中,并通过 val transactions: List<String> 对外提供。deposit(amount) 和 withdraw(amount) 成功时返回 true:小于 1 的金额会被拒绝,超过余额的取款也会被拒绝;成功的变更会记录为 +50 或 -20。statement() 返回 Ada: 30 (+50, -20) 或 Ada: 0 (no transactions)。

提供的代码会读取 owner 和开户存款(name,amount),然后读取 d n 或 w n 命令。命令失败时会输出 refused,最后输出账户对账单;账户信息无效时会输出错误消息。

你的代码写在 BankAccount.kt 中。Main.kt 保存了提供的输入和输出代码,不能编辑。

亲手试试

fun main() {
    // 提供的输入/输出代码:保持原样
    val input = generateSequence(::readLine).toList()
    try {
        val (name, amount) = input[0].split(",")
        val account = BankAccount(name, amount.toInt())
        for (cmd in input.drop(1)) {
            val (op, n) = cmd.split(" ")
            val ok = if (op == "d") account.deposit(n.toInt()) else account.withdraw(n.toInt())
            if (!ok) println("refused")
        }
        println(account.statement())
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }
}

面向对象编程中的所有课

自己练习: Kotlin 在线编辑器