1.1 在Scala REPL中键入3,然后按Tab键。有哪些方法可以被应用?
!= < >>> doubleValue isNaN isValidShort shortValue toDouble toShort
% << ^ floatValue isNegInfinity isWhole signum toFloat unary_+ & <= abs floor isPosInfinity longValue to toHexString unary_- * == byteValue getClass isValidByte max toBinaryString toInt unary_~ + > ceil intValue isValidChar min toByte toLong underlying - >= compare isInfinite isValidInt round toChar toOctalString until / >> compareTo isInfinity isValidLong self toDegrees toRadians | |
1.2 在Scala REPL中,计算3的平方根,然后再对该值求平方。现在,这个结果与3相差多少?(提示:res变量是你的朋友)
scala> import scala.math._
import scala.math._
scala> sqrt(3) res5: Double = 1.7320508075688772
scala> 3-res5 res6: Double = 1.2679491924311228 |
1.3 res变量是val还是var?
res变量是val
1
2 3 4 |
scala> res5=6
<console>:15: error: reassignment to val res5=6 ^ |
1.4 Scala允许你用数字去乘字符串—去REPL中试一下”crazy”*3。这个操作做什么?在Scaladoc中如何找到这个操作?
1
2 |
scala> "crazy" * 3
res7: String = crazycrazycrazy |
scala docs 去查StringOps https://www.scala-lang.org/api/current/scala/collection/immutable/StringOps.html
1.5 10 max 2的含义是什么?max方法定义在哪个类中?
返回两者中比较大的一个
max方法定义在RichInt方法中。
https://www.scala-lang.org/api/current/scala/runtime/RichInt.html
1
2 |
scala> 10 max 2
res8: Int = 10 |
1.6 用BigInt计算2的1024次方
1
2 |
scala> BigInt(2).pow(1024)
res9: scala.math.BigInt = 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216 |
1.7 为了在使用probablePrime(100,Random)获取随机素数时不在probablePrime和Radom之前使用任何限定符,你需要引入什么?
import需要的包。Random在scala.util中,而probablePrime是BigInt中的方法。
1
2 3 4 5 6 7 8 |
scala> import scala.math.BigInt._
import scala.math.BigInt._
scala> import scala.util.Random import scala.util.Random
scala> probablePrime(100,Random) res10: scala.math.BigInt = 972068772675126914675474417693 |
1.8 创建随机文件的方式之一是生成一个随机的BigInt,然后将它转换成三十六进制,输出类似”qsnvbevtomcj38o06kul”这样的字符串。查阅Scaladoc,找到在Scala中实现该逻辑的办法。
1
2 |
scala> scala.math.BigInt(scala.util.Random.nextInt).toString(36)
res11: String = rla4ni |
1.9 在Scala中如何获取字符串的首字符和尾字符?
1
2 3 4 5 6 7 8 9 10 11 |
scala> "Hello"(0)
res12: Char = H
scala> "Hello".take(1) res13: String = H
scala> "Hello".reverse(0) res14: Char = o
scala> "Hello".takeRight(1) res15: String = o |
1.10 take,drop,takeRight和dropRight这些字符串函数是做什么用的?和substring相比,他们的优点和缺点都是哪些?
take,drop,takeRight,dropRight适合从两边处理字符串,很方便可以配合使用,substring适合处理中间的字符串。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
scala> "Hello world!".take(2)
res19: String = He
scala> "Hello world!".takeRight(3) res20: String = ld!
scala> "Hello world!".drop(3) res21: String = lo world!
scala> "Hello world!".dropRight(4) res22: String = Hello wo
scala> "Hello world!".take(2).drop(1) res23: String = e |