scala简单的功能实现~weektwo

Scala编程实战
本文详细介绍了Scala编程语言的应用,包括BankAccount类的实现,用于管理存款和取款操作;Person类的创建,用于处理个人姓名信息;Point类的定义,允许直接使用Point(x,y)创建实例;以及OrderedPoint类的开发,用于按词典方式排序点对象。

1、编写⼀个BankAccount类,假如deposit和withdraw⽅法,和⼀个只读的balance属性。

//存款(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
}

2、编写Person类,主构造器接受⼀个字符串,字符串形式为名字,空格,姓,如 new Person(“Fred Smith”)。提供只读属性firstName和lastName。

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"
}

3、定义⼀个Point类,使得我们不⽤new就可以直接使⽤Point(3,4)来构建类的实例。

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)
}

4、通过把scala.math.Ordered[Point]混⼊java.awt.Point⽅式,定义OrderedPoint类。按词典⽅式进 ⾏排序,也就是说,如果x1 < x2 或者 x1 = x2 且 y1 < y2, 则(x1,y1) < (x2, y2) 

 

转载于:https://www.cnblogs.com/xiao02fang/p/10320085.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值