scala簡單的功能實現~weektwo

一、編寫⼀個BankAccount類,假如deposit和withdraw⽅法,和⼀個只讀的balance屬性。java

//存款(deposit)和取款()函數

class BankAccount extends App{
  private  var account:Int=0
  def deposit(money : Int){
    account += money
    println(s"the whole money is $account")
  }
  def withdraw(money : Int){
    //assert(conditon)將在條件不成立的時候,拋出assertionError
    //assert(conditon,explanation)講在條件不成立的時候,拋出explanation做爲說明
    assert(money<=account,"The money you withdraw should be less than account")
    account -=money
    println(s"the whole money is $account")
  }
  def balance=account
}

二、編寫Person類,主構造器接受⼀個字符串,字符串形式爲名字,空格,姓,如 new Person(「Fred Smith」)。提供只讀屬性firstName和lastName。app

class Person {
  val name="Fred Smith"
  val _name=name.split("\\s+")
  val firstName=_name(0)
  val lastName=_name(1)
  override def toString=s"the first name is $firstName,the last name is $lastName"
}

三、定義⼀個Point類,使得咱們不⽤new就能夠直接使⽤Point(3,4)來構建類的實例。less

class Point(val x:Int=0,val y:Int=0) {
  override def toString=("Point x is "+x+",Point y is "+y)
}
object Point{
  def apply(x:Int=0,y:Int=0)=new Point(x,y)
}

四、經過把scala.math.Ordered[Point]混⼊java.awt.Point⽅式,定義OrderedPoint類。按詞典⽅式進 ⾏排序,也就是說,若是x1 < x2 或者 x1 = x2 且 y1 < y2, 則(x1,y1) < (x2, y2) ide

相關文章
相關標籤/搜索