期末试题

33 阅读1分钟

你正在设计一个二维游戏的界面,需要用很多的点来表示游戏中的角色。

设计一个Point类,其x和y可以通过构造器提供。

它有几个方法:

1. 方法1: 计算自己在哪个象限。 whereAmI():String

2. 方法2: 计算和坐标原点的距离。getDist():Double

3. 方法3: 计算与另一个点的距离。fromPoint(other:Point):Double

4. 方法4: 重写equals 判断是否是同一个点(x和y都相等就是同一个点)。

5. 方法5: 重写toString,更友好的输出点的信息。

再设计一个子类LabelPoint它来继承Point类,其构造器接收一个标签值和x,y坐标。

例如: New LabelPoint("black",1,2)

class Point(var x:Double, var y:Double) {
  def whereAmI():String = {
    if(x >0 && y >0){
      "第1象限"
    } else if(x>0 && y < 0){
      "第4象限"
    } else if(x<0 && y < 0){
      "第3象限"
    }else if(x<0 && y > 0){
      "第2象限"
    } else if(x ==0 && y != 0){
      "y轴上"
    } else if(y ==0 && x != 0){
      "x轴上"
    } else if(x ==0 && x == 0){
      "原点"
    } else {
      "未知"
    }
  }
  def getDist():Double = {
    Math.sqrt( this.x * this.x + this.y * this.y )
  }

  def fromPoint(other:Point):Double = {
    Math.sqrt( (this.x-other.x) * (this.x-other.x) + (this.y-other.y) * (this.y-other.y ) )
  }

  override def equals(obj: Any): Boolean = {
    val other = obj.asInstanceOf[Point]
    this.x == other.x && this.y == other.y
  }

  override def toString: String = {
    s"Point(${x}, ${y})"
  }
}

def main(args: Array[String]): Unit = {
  val p1 = new Point(1, 1)
  val p2 = new Point(1, 1)
  println(p1 == p2)
  println(p1.whereAmI())
  println(p1.getDist())
  println(p1.fromPoint(p2))

}