快學scala第一章習題答案
2.1 在Scala REPL中鍵入3,然後按Tab鍵。有哪些方法可以被應用?
這個。。。。直接操作一遍就有結果了.此題不知是翻譯的問題,還是原題的問題,在Scala REPL中需要按3. 然後按Tab才會提示。 直接按3加Tab是沒有提示的。下面是結果
Scala程式碼
1. != ## % & * +
2. - / < << <= ==
3. > >= >> >>> ^ asInstanceOf
4. equals getClass hashCode isInstanceOf toByte toChar
5. toDouble toFloat toInt toLong toShort toString
6.
列出的方法並不全,需要查詢全部方法還是需要到Scaladoc中的Int,Double,RichInt,RichDouble等類中去檢視。
2.2 在Scala REPL中,計算3的平方根,然後再對該值求平方。現在,這個結果與3相差多少?(提示:res變數是你的朋友)
依次進行計算即可
Scala程式碼
1. scala> scala.math.sqrt(3)
2. warning: there were 1 deprecation warnings; re-run with -deprecation for details
3. res5: Double = 1.7320508075688772
4.
5. scala> res5*res5
6. res6: Double = 2.9999999999999996
7.
8. scala> 3 - res6
9. res7: Double = 4.440892098500626E-16
2.3 res變數是val還是var?
val是不可變的,而var是可變的,只需要給res變數重新賦值就可以檢測res是val還是var了
Scala程式碼
1. scala> res9 = 3
2. <console>:8: error: reassignment to val
3. res9 = 3
4. ^
2.4Scala允許你用數字去乘字串—去REPL中試一下"crazy"*3。這個操作做什麼?在Scaladoc中如何找到這個操作?
Scala程式碼
1. scala> "crazy"*3
2. res11: String = crazycrazycrazy
從程式碼可以推斷,*是"crazy"這個字串所具有的方法,但是Java中的String可沒這個方法,很明顯。此方法在StringOps中。
2.5 10max 2的含義是什麼?max方法定義在哪個類中?
直接在REPL中執行
Scala程式碼
1. scala> 10 max 2
2. res0: Int = 10
3.
4. scala> 7 max 8
5. res1: Int = 8
6.
7. scala> 0 max 0
8. res2: Int = 0
可以看出,此方法返回兩個數字中較大的那個。此方法Java中不存在,所以在RichInt中。
2.6 用BigInt計算2的1024次方
簡單的API呼叫
Scala程式碼
1. scala> BigInt(2).pow(1024)
2. res4: scala.math.BigInt = 1797693134862315907729305190789024733617976978942306572734300811577326758055009631327084773224
3. 075360211201138798713933576587897688144166224928474306394741243777678934248654852763022196012460941194530829520850057688
4. 38150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
2.7 為了在使用probablePrime(100,Random)獲取隨機素數時不在probablePrime和Radom之前使用任何限定符,你需要引入什麼?
so easy. import需要的包啊。Random在scala.util中,而probablePrime是BigInt中的方法,引入即可
Scala程式碼
1. import scala.math.BigInt._
2. import scala.util.Random
3.
4. probablePrime(3,Random)
2.8 建立隨機檔案的方式之一是生成一個隨機的BigInt,然後將它轉換成三十六進位制,輸出類似"qsnvbevtomcj38o06kul"這樣的字串。查閱Scaladoc,找到在Scala中實現該邏輯的辦法。
到BigInt中查詢方法。
Scala程式碼
1. scala> scala.math.BigInt(scala.util.Random.nextInt).toString(36)
2. res21: String = utydx
2.9 在Scala中如何獲取字串的首字元和尾字元?
Scala程式碼
1. //獲取首字元
2. "Hello"(0)
3. "Hello".take(1)
4. //獲取尾字元
5. "Hello".reverse(0)
6. "Hello".takeRight(1)
2.10take,drop,takeRight和dropRight這些字串函式是做什麼用的?和substring相比,他們的優點和缺點都是哪些?
查詢API即可 take是從字串首開始獲取字串,drop是從字串首開始去除字串。takeRight和dropRight是從字串尾開始操作。 這四個方法都是單方向的。 如果我想要字串中間的子字串,那麼需要同時呼叫drop和dropRight,或者使用substring