1. 程式人生 > >《快學Scala》第六章習題解答

《快學Scala》第六章習題解答

RT。

package com.scalalearn.scala.main
/**
  * 快學scala 06習題
  */

//1.編寫一個Conversions物件,加入inchesToCentimeters,gallonsToLiters和milesToKilometers方法
object Conversions{
  def inchesToCentimeters(input:BigInt):BigInt={
    //省略...
    input
  }

  def gallonsToLiters(input:BigInt):BigInt={
    //省略...
    input
  }

  def milesToKilometers(input:BigInt):BigInt={
    //省略...
    input
  }
}

//2.前一個不是很面向物件,提供一個通用的超類UnitConversion並定義超類的InchesToCentimeters,GallonsToLiters和MilesToKilometers物件
abstract class UnitConversion{
  def transform(input:BigInt):BigInt;
}

object InchesToCentimeters extends UnitConversion{
  def transform(input:BigInt):BigInt = {
    //省略...
    input
  }
}
object GallonsToLiters extends UnitConversion{
  def transform(input:BigInt):BigInt = {
    //省略...
    input
  }
}
object MilesToKilometers extends UnitConversion{
  def transform(input:BigInt):BigInt = {
    //省略...
    input
  }
}

//4.定義一個Point類和一個伴生物件,使得我們不用new而是直接用Point(3,4)來構造Point例項
class Point(px:Int,py:Int){
  var x:Int = 0
  var y:Int = 0

  x = px
  y = py
}

object Point{
  def apply(px:Int,py:Int):Unit = {
    new Point(px,py)
  }
}

//6.用一個列舉撲克牌的四種花色
class PokerCard{}

object PokerCard extends Enumeration{
  val HEART = Value(0)
  val SPADE = Value(1)
  val CLUB = Value(2)
  val DIAMOND = Value(3)
}

//8.用列舉描述RGB立方體的8個角,ID用色值表示
object RGBCube extends Enumeration{
  //我這裡就不真的對應色值了;就上4個角和下4個角分別定義一下
  val top1 = Value(0)
  val top2 = Value(1)
  val top3 = Value(2)
  val top4 = Value(3)
  val bottom1 = Value(4)
  val bottom2 = Value(5)
  val bottom3 = Value(6)
  val bottom4 = Value(7)
}

object LearnScala06 {
  //7.寫一個檢測撲克牌花色是否為紅色的函式
  def checkColor(pokerCard:PokerCard.Value):Boolean = {
    if(pokerCard == PokerCard.HEART || pokerCard == PokerCard.DIAMOND){
      true
    }else{
      false
    }
  }

  def main(args:Array[String]):Unit = {
    println("================execise6==================")
    val point = Point(3,4)

    println("================execise7==================")
    println(LearnScala06.checkColor(PokerCard.HEART))
  }
}