1. 程式人生 > >Scala程式設計思想的課後練習答案

Scala程式設計思想的課後練習答案

1、類和物件

package SecondDemo

import com.AtomicTest.AtomicTest._

/**
  * Created by Administrator on 2016/12/27.
  */
object ClassAndObject {
  def main(args: Array[String]): Unit = {
    //region Exercise1
    /* val r = Range(0, 10)
     val st = r.step
     st is 1
     val r1 = Range(0, 10, 3)
     val st1 = r1.step
     st1 is 3
*/ //endregion //region Exercise2 /*var str1 = new String var result = "" str1 = "This is an experiment" for (i <- str1.split(" ")) { result += i } result is "Thisisanexperiment"*/ //endregion //region Exercise3 /*var s1 = new String s1 = "Sally" var s2 = new
String s2 = "Sally" var result = "" if (s1.equals(s2)) { result = "s1 and s2 are equal" } else { result = "s1 and s2 are not equal" } result is "s1 and s2 are equal"*/ //endregion //region Exercise4 /* val h = new Hippo val l = new Lion val l2 = new Lion val
t = new Tiger val m = new Monkey val g = new Giraffe val g1 = new Giraffe val g2 = new Giraffe val z = new Zebra println(z) println(h) println(l) println(l2) println(t) println(m) println(g) println(g1) println(g2)*/ //endregion } } //region Exercises_class /* class Hippo class Lion class Tiger class Monkey class Giraffe class Zebra { println(" i hvae stripes") } */ //endregion

2、 域

package SecondDemo

import com.AtomicTest.AtomicTest._

/**
  * Created by Administrator on 2016/12/27.
  */
object ExerciseDemo {
  def main(args: Array[String]): Unit = {
    //region Exercise1
    /*val cup2 = new Cup2
    cup2.add(45) is 45
    cup2.percentFull is 45
    cup2.add(-15) is 30
    cup2.percentFull is 30
    cup2.add(-50) is -20
    cup2.percentFull is -20*/
    //endregion
    //region Exercise2
    /*val cup2 = new Cup2
    cup2.add(45) is 45
    cup2.add(-50) is 0
    cup2.add(10) is 10
    cup2.add(-9) is 1
    cup2.add(-2) is 0*/
    //endregion
    //region Exercise3
    /* val cup2 = new Cup2
     cup2.percentFull = 56
     cup2.percentFull is 56*/
    //endregion
    //region Exercise4
    /*val cup4 = new Cup4
    cup4.set(56)
    cup4.get() is 56*/
    //endregion
  }
}
//region Exercise4_class
/*class Cup4 {
  var peacentFull = 0;
  val max = 100

  def set(value: Int): Unit = {
    peacentFull = value
  }

  def get(): Int = {
    peacentFull
  }

  def add(increase: Int): Int = {
    peacentFull += increase
    if (peacentFull > max) peacentFull = max
    else if (peacentFull < 0) peacentFull = 0
    peacentFull
  }
}*/
//endregion
//region Exercise1,2,3_class
/*
class Cup2 {
  var percentFull = 0
  val max = 100

  def add(increase: Int): Int = {
    percentFull += increase
    if (percentFull > max) {
      percentFull = max
    } else if (percentFull < 0) {
      percentFull = 0
    }
    percentFull //return this value
  }
}
*/
//endregion

for迴圈

package SecondDemo

import com.AtomicTest.AtomicTest._

/**
  * Created by Administrator on 2016/12/27.
  */
object ForDemo {
  def main(args: Array[String]): Unit = {
    //region Example
    /*var result = ""
    for (i <- 0 to 9) {
      result += i + " "
    }
    result is "0 1 2 3 4 5 6 7 8 9 "

    result = ""
    for (i <- 0 until (10)) {
      result += i + " "
    }
    result is "0 1 2 3 4 5 6 7 8 9 "

    result = ""
    for (i <- Range(0, 10)) {
      result += i + " "
    }
    result is "0 1 2 3 4 5 6 7 8 9 "

    result = ""
    for (i <- Range(0, 10, 2)) {
      result += i + " "
    }
    result is "0 2 4 6 8 "

    var sum = 0
    for (i <- Range(0, 20, 2)) {
      println("adding " + i + "to " + sum)
      sum += i
    }
    sum is 90
  */
    //endregion
    //region Exercise
    /*val r1 = Range(0,10).inclusive
    val r2 = r1(10)
    r2 is 10*/
    //endregion
    //region Exercise1
    /* var sum = 0
     for (i <- Range(0, 10).inclusive) {
       sum += i
     }
     sum is 55
   */
    //endregion
    //region Exercise2
    /* var sum = 0
     for (i <- Range(1, 10).inclusive) {
       if (i % 2 == 0) {
         sum += i
       }
     }
     sum is 30*/
    //endregion
    //region Exercise3
    /*  var evens = 0
      var odds = 0
      for (i <- 0 until 11) {
        if (i % 2 == 0) {
          evens += i
        } else {
          odds += i
        }
      }
      odds is 25
      evens is 30
      (odds + evens) is 55*/
    //endregion
  }
}

類中的方法

package SecondDemo

import com.AtomicTest.AtomicTest._

/**
  * Created by Administrator on 2016/12/27.
  */
object MethodInClass {
  def main(args: Array[String]): Unit = {
    //region Lizi
    /*    val c = new cat
        c.meow() is "mew!"
        val d = new Dog
        d.exercise() is "squeak Running on wheel"*/
    //endregion
    //region Excises1
    /*val sailBoat = new SailBoat
    sailBoat.raise() is "Sails raised"
    sailBoat.lower() is "Sails lowered"
    val motorBoat = new MotorBoat
    motorBoat.MotorOff() is "Motor off"
    motorBoat.MotorOn() is "Motor on"*/
    //endregion
    //region Excises2
    /*val flare = new Flare
    val f1 = flare.light()
    f1 is "Flare used!"*/
    //endregion
    //region Excise3
    /* val sailBoat = new SailBoat
     sailBoat.single() is "Flare used!"
     val motorBoat = new MotorBoat
     val m = motorBoat.single()
     m is "Flare used!"*/
    //endregion
  }
}

//region Excises2_class
/*class Flare {
  def light(): String = {
    "Flare used!"
  }
}*/

//endregion
//region Excises1_Class
/*
class SailBoat {
  def raise(): String = {
    "Sails raised"
  }

  def single(): String = {
    val f = new Flare
    f.light()
  }

  def lower(): String = {
    "Sails lowered"
  }
}

class MotorBoat {
  def MotorOn(): String = {
    "Motor on"
  }

  def single(): String = {
    val f = new Flare
    f.light()
  }

  def MotorOff(): String = {
    "Motor off"
  }
}
*/

//endregion
//region Lizi_Class
/*
class cat {
  def meow(): String = {
    "mew!"
  }
}

class Dog {
  def speak(): String = {
    "squeak "
  }

  def exercise(): String = {
    speak() + "Running on wheel"
  }
}
*/
//endregion

5、if條件

package SecondDemo

import com.AtomicTest.AtomicTest._

/**
  * Created by Administrator on 2016/12/27.
  */
object MoreIfDemo {
  def main(args: Array[String]): Unit = {
    //region Example
    /* val b = 1
     TrueOrFalse(b < 3) is "It's true"
     TrueOrFalse(b > 3) is "It's false"*/
    //endregion
    //region Exercise
    /*IsPalindrome("Mom") is true
    IsPalindrome("dad") is true
    IsPalindrome("love") is false
    IsPalindrome("DAD") is true
    IsPalindrome("Blob") is false*/
    //endregion
    //region Exercise1
    /*isPalIgnoreSpecial("Madam I'm adam") is true*/
    //endregion
  }
  //region Exercise1_function
  /*  def isPalIgnoreSpecial(str: String): Boolean = {
      var createdStr = ""
      for (c <- str) {
        val theValue = c.toInt
        if (theValue <= 122 && theValue >= 65) {
          createdStr += c
        } else if (theValue <= 57 && theValue >= 48) {
          createdStr += c
        }
      }
      val cs = createdStr.toLowerCase
      if (cs.reverse.equals(cs)) {
        true
      } else {
        false
      }
   }*/

  //endregion
  //region Exercise_function
  /*def IsPalindrome(str: String): Boolean = {
    val str1 = str.toLowerCase
    if (str1.reverse.equals(str1)) {
      true
    } else {
      false
    }
  }*/
  //endregion
  //region Example_function
  /* def TrueOrFalse(exp: Boolean): String = {
     if (exp) {
         "It's true"
     }
     else {
       "It's false"
     }
   }
 */
  //endregion
}

6、匯入包

package SecondDemo

import com.AtomicTest.AtomicTest._

/**
  * Created by Administrator on 2016/12/27.
  */
object PackageDemo {
  def main(args: Array[String]): Unit = {
    //region Example
    /*calculateBMI(160, 68) is "Normal weight"
    calculateBMI(100, 68) is "UnderWeight"
    calculateBMI(200, 68) is "OverWeight"*/
    //endregion
    //region Excises1
    /*val myValue1 = 20
    myValue1 is 20
    val myValue2 = 10
    myValue2 is 10
    val myValue3 = 30
    val myValue4 = 40
    myValue3.equals(myValue4) is false
    val myValue5 = "10"
    myValue2.equals(myValue5) is false*/
    //endregion
    //region Excises2
    /* squareArea(1) is 1
     squareArea(2) is 4
     squareArea(5) is 25
     rectangleArea(2, 2) is 4
     rectangleArea(5, 4) is 20
     trapezoidArea(2, 2, 4) is 8
     trapezoidArea(3, 4, 1) is 3.5*/
    //endregion
  }

  def squareArea(x: Int): Int = {
    x * x
  }

  def rectangleArea(x: Int, y: Int): Int = {
    x * y
  }

  def trapezoidArea(x: Double, y: Double, h: Double): Double = {
    h / 2 * (x + y)
  }

  def calculateBMI(lbs: Double, height: Double): String = {
    val bml = lbs / (height * height) * 703.07
    if (bml < 18.5) {
      "UnderWeight"
    } else if (bml < 25) {
      "Normal weight"
    } else {
      "OverWeight"
    }
  }
}

7、”井“棋盤練習

package SecondDemo

import com.AtomicTest.AtomicTest._

/**
  * Created by Administrator on 2016/12/27.
  */
object SumaryExerciseDemo {
  def main(args: Array[String]): Unit = {
    //region Exercise1
    /* ConnectionCharVector()
     ConnectionIntVector()
     ConnectionStringVector()*/
    //endregion
    //region Exercise2
    /* val s = ConnectionThreeVector()
     println(s)*/
    //endregion
    //region Example
    val grid = new Grid

    grid.play('X', 1, 1) is "successful move"
    grid.play('X', 1, 1) is "invalid move"
    grid.play('O', 1, 3) is "invalid move"
    //endregion
  }



  //region Exercise2_function
  /*def ConnectionThreeVector(): String = {
    val charVector = Vector('c', 'b', 'l', 'o', 'e', 'v')
    val stringVector = Vector("I", "love", "you", "for", "ever")
    val intVector = Vector(1, 2, 3, 4, 5)
    val threeVector = Vector(charVector, stringVector, intVector)
    var result = ""
    for (i <- threeVector) {
      for (j <- i) {
        result += j + " "
      }
    }
    result
  }*/
  //endregion
  //region Exercise1_function
  /*def ConnectionCharVector(): Unit = {
    val charVector = Vector('c', 'b', 'l', 'o', 'e', 'v')
    val maxChar = charVector.max
    maxChar is 'v'
    val minChar = charVector.min
    minChar is 'b'
    var result = ""
    for (i <- charVector.sorted) {
      result += i + " "
    }
    result is "b c e l o v "
  }

  def ConnectionStringVector(): Unit = {
    val stringVector = Vector("I", "love", "you", "for", "ever")
    val maxString = stringVector.max
    maxString is "you"
    val minString = stringVector.min
    minString is "I"
    var result = ""
    for (i <- stringVector.sorted) {
      result += i + " "
    }
    result is " ever for love you "
  }

  def ConnectionIntVector(): Unit = {
    val intVector = Vector(1, 2, 3, 4, 5)
    val maxInt = intVector.max
    maxInt is 5
    val minInt = intVector.min
    minInt is 1
    var result = ""
    for (i <- intVector) {
      result += i + " "
    }
    result is "1 2 3 4 5 "
  }*/
  //endregion
}

class Cell {
  var entry = '*'

  def set(e: Char): String = {
    if (entry == '*' && (e == 'X' || e == 'O')) {
      entry = e
     return "successful move"
    } else {
      "invalid move"
    }
  }
}

class Grid {
  val cells = Vector(Vector(new Cell, new Cell, new Cell), Vector(new Cell, new Cell, new Cell), Vector(new Cell, new Cell, new Cell))

  def ShowCheckeroard(): Unit = {
    for (i <- cells) {
      for (j <- i) {
        print(j.entry)
      }
      println
    }
  }

  def play(e: Char, x: Int, y: Int): String = {
    ShowCheckeroard()
    if (x < 0 || x > 2 || y < 0 || y > 2) {
      "invalid move"
    } else {
      cells(x)(y).set(e)
    }

  }
}

8、Vector

package SecondDemo

import com.AtomicTest.AtomicTest._

/**
  * Created by Administrator on 2016/12/27.
  */
object VectorDemo {
  def main(args: Array[String]): Unit = {
    //region Example
    /*val v1 = Vector(1, 2, 3, 4, 7, 10)
    v1 is Vector(1, 2, 3, 4, 7, 10)
    v1(4) is 7
    var result = ""
    for (i <- v1) {
      result += i + " "
    }
    result is "1 2 3 4 7 10 "
    val v3 = Vector(1.1,2.2,3.3,4.4)
    v3.reverse is Vector(4.4,3.3,2.2,1.1)
    var v4 = Vector("Twas","Brillig","And","Slithy","Toves")
    v4 is Vector("Twas","Brillig","And","Slithy","Toves")
    v4.sorted is Vector("And","Brillig","Slithy","Toves","Twas")
    v4.head is "Twas"
    v4.tail is Vector("Brillig","And","Slithy","Toves")*/
    //endregion
    //region Exercise1
    /*  val v = Vector("The", "dog", "visited", "the", "firehouse")
      var s = ""
      for (i <- v) {
        println(i)
        s += i + " "
      }
      s = s.replace("firehouse ","firehouse!")
      s is "The dog visited the firehouse!"*/
    //endregion
    //region Exercise2
    /*  val v = Vector("The", "dog", "visited", "the", "firehouse")
      var s = ""
      for (i <- v) {
        s = i.reverse
        println(s)
      }*/
    //endregion
    //region Exercise3
    /* var v = Vector("The", "dog", "visited", "the", "firehouse")
     v = v.reverse
     for (i <- v) {
       println(i)
     }*/
    //endregion
    //region Exercise4
    /*val v1 = Vector(1, 2, 3, 4, 5)
    val v2 = Vector(1.1, 2.2, 3.3, 4.4, 5.5)
    v1.sum is 15
    v1.min is 1
    v1.max is 5
    v2.sum is 16.5
    v2.min is 1.1
    v2.max is 5.5*/
    //endregion
    //region Exercise5
    /* val v = Vector("I", "love", "you", "angle", "ming", "tian", "iloveyouangleming", "zoo")
     //println(v.sum)
     v.min is "angle" //min 表示Vector中字串的首字母的ASCLL碼值的大小排序取出最小值
     v.max is "zoo" //max 表示Vector中字串的的首字母的ASCLL碼值的大小排序取出最大值
     /* println(v.min)
      println(v.max)*/*/
    //endregion
    //region Exercise6
    /* val l = List("i", "love", "you", "angel", "ming")
     val r = l.reverse //將List中的字串翻轉形成一個新的List("ming","angel","you","love","i")
     val r1 = l.sorted //將List中的字串按照字母表排序形成一個新的List ("angle","i","love","ming","you")
                       //Set集合是沒有reverse和sorted的操作的
     for (i <- r) {
       println(i)
     }
     for (i <-r1){
       println(i)
     }
     for (i <- l) {
       println(i)
     }*/
    //endregion
    //region Exercise7
    /* val myValue1 = Vector(1, 2, 3, 4, 5, 6)
     val myValue2 = Vector(1, 2, 3, 4, 5, 6)
     myValue1.equals(myValue2) is true*/
    //endregion
  }

}

備註:Set與List的操作方法與Vector一樣,只不過略有區別