0
点赞
收藏
分享

微信扫一扫

ScalaNote07-类的练习题

倪雅各 2022-08-04 阅读 34


  整几道练习题做做~

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 条评论