ScalaNote07-类的练习题

  整几道练习题做做~

Exercises 1

  编写一个Time类,加入只读属性hours和minutes,和一个检查某一时刻是否早于另一时刻的方法before(other:Time):Boolean。Time对象应该以new Time(hrs,min)方式构建。

class Time(inHour:Int,inMinutes:Int){ // 主构造器进行值的初始化
    // 定义两个属性
    val hour = inHour 
    val minutes = inMinutes 
    // 定义方法
    //     这里this.不用好像也可以
    //     判断逻辑就不说了,很简单
    //     : Boolean = {}需要注意下,又忘记了
    def before(other:Time): Boolean = {
        if(this.hour<other.hour){
            return true
        }else if(this.hour>other.hour){
            return false
        }else if(this.minutes<other.minutes){
            return true
        }else{
            return false
        }
    }
}
val cur = new Time(9, 20)
val other = new Time(8, 20)
println(cur.before(other)) 
false





defined class Time
cur: Time = Time@389b07bb
other: Time = Time@4e9aed33

Exercises 2

编写一个BankAccount类,要求:

  • 有余额属性,该属性可读不可写
  • 取款方法,需要判断取款金额小于余额
  • 存款方法,要求存款金额大于0
  • 查询方法,对余额进行查询

假设我们在银行已经开户,并且预存了100元。完成以下操作:

  • 查询余额
  • 存600元
  • 取34元
  • 查询余额
class BankAccount {

  private var balance = 100

  def deposit(amount: Int): Unit = {
    if (amount > 0) balance = balance + amount
  }

  def withdraw(amount: Int): Int ={
    if (0 < amount && amount <= balance) {
      balance = balance - amount
      balance
    } else throw new Error("insufficient funds")      
  }
 def query{
     println("Your balance: "+this.balance)
 }
}
val simple = new BankAccount
simple.query
simple.deposit(600)
simple.withdraw(34)
simple.query
Your balance: 100
Your balance: 666





defined class BankAccount
simple: BankAccount = BankAccount@554ac8de

  感觉这样编程好像还挺好玩的,有机会再找几个题目练习练习吧~

                                2020-02-22 于南京市栖霞区

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值