快学Scala 第五章 类 课后习题

这是一系列关于Scala编程的课后习题,涵盖了类的改进、银行账户管理、时间比较、学生信息、Person类设计、Car类构造器以及与其他语言的对比,旨在加深对Scala类和对象的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 改进5.1的Counter类,让它不要再Int.MaxValue时变成负数
class Counter{
  private var value = 0

  def increment()={
    if(value ==Int.MaxValue) value.toLong
    value += 1
  }
  
  def current =value
}
2. 编写一个BankAccount类,加入deposit和withdraw方法,和一个只读的balance属性。
class BankAccount{
  private var balance = 0.0
  //存钱
  def deposit(money:Double)={
    balance += money
  }
  //qiu钱
  def withDraw(money:Double)={
    if(balance >= money) {
      balance -=money
    }else{
      throw new Exception("money not enough")
    }
  }
  //查询余额
  def getBalance = balance

}
3. 编写个Time类,加入只读属性hours和minutes,和一个检查某一时刻是否早于另一时刻的方法before(other:Time):Boolean。Time对象应该以new Time(hrs,min)方式构建,其中hrs小时的格式是以军用时间格式呈现的(介于0和23之间)
class MyTime( h :Int =0, m:Int = 0){


  private var hours:Int=0
  private var minutes:Int = 0

  //时间逻辑校验
  if(h>= 0 & h <=23){
     this.hours=h
  }else{  throw new Exception("consture time error")}

  if(m >=0 & m<=59){
    this.minutes = m
  }else{throw new Exception("consture time error")}

  //判断时间是否早于当前
  def befor(other:MyTime)={
     if(this.hours > other.hours) true
     else if (this.hours ==other.hours & this.minutes >other.minutes) true
     else false
  }

  //获取时间
  def getHours =this.hours
  def getMinutes = this.minutes

4. 重新实现前一个练习中的Time类,将内部呈现改成自午夜起的分钟数(介于 0 到 24*60-1之间)。不要改变公有接口。也就是说,客户端代码不应因为你的修改而受到影响。
class MyTime2(var h:Int=0,var m : 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值