scala> 3.% * - > >> ^ isInstanceOf toChar toFloat toLong toString unary_- |& + / >= >>> asInstanceOf toByte toDouble toInt toShort unary_+ unary_~2. 在Scala REPL中,计算3的平方根,然后再对该值求平方。现在,这个结果与3相差多少?(提示:res变量是你的朋友。)
scala> import scala.math._import scala.math._scala> sqrt(3)res1: Double = 1.7320508075688772scala> res1 * res1res2: Double = 2.9999999999999996scala> 3 - res2res3: Double = 4.440892098500626E-16 |
3. res变量是val还是var?
res变量是val。
scala> res3=0<console>:16: error: reassignment to val res3=0 ^4. Scala允许你用数字去乘字符串—去REPL中试一下 "crazy" * 3 。这个操作做什么?在Scaladoc中如何找到这个操作?
scala> "crazy" * 3res4: String = crazycrazycrazy- 在过滤框中输入 String - 选择 StringOps - 找到 * 方法,文档中的说明如下: def *(n: Int): String Return the current string concatenated n times. |
5. 10 max 2 的含义是什么?max 方法定义在哪个类中?
求整数中的较大者。max 方法定义在RichInt类中。
def max(that: Int): Int
Returns this if this > that or that otherwise.
Implicit information This member is added by an implicit conversion from Int to RichInt performed by method intWrapper in scala.LowPriorityImplicits.
Definition Classes RichInt → ScalaNumberProxy
6. 用BigInt计算2的1024次方。
scala>import scala.math._ // OR import math._
scala> pow(2,1024)
res8: Double = Infinity
scala> BigInt(2).pow(1024)
res9: scala.math.BigInt = 1797693134862315907729305190789024733617976978942306572734300811577326758055009631327084773224075360211201138798713933576587897688144166224928474306394741243777678934248654852763022196012460941194530829520850057688381506823424628
7. 为了在使用probablePrime(100, Random)获取随机素数时不在 probablePrime 和 Random 之前使用任何限定符,你需要引入什么?
scala> import scala.util.Randomimport scala.util.Randomscala> import scala.math.BigInt._import scala.math.BigInt._scala> probablePrime(100,Random)res12: scala.math.BigInt = 1220680273650327122886980473381 |
8. 创建随机文件的方式之一是生成一个随机的 BigInt,然后将它转换成三十六进制,输出类似"qsnvbevtomcj38o06ku1"这样的字符串。查阅Scaladoc,找到在Scala中实现该逻辑的办法。
从Scaladoc中,我找到BigInt的如下方法:
def toString(radix: Int): String
Returns the String representation in the specified radix of this BigInt.
在REPL中实验:
scala> probablePrime(100,Random)res12: scala.math.BigInt = 1220680273650327122886980473381scala> probablePrime(100,Random).toString(36)res13: String = 2f1yebpp8l5ft8y2afh79. 在Scala中如何获取字符串的首字符和尾字符?
scala> val str = "Hello"str: String = Helloscala> str(0)res14: Char = Hscala> str.headres16: Char = Hscala> str.lastres17: Char = o10. take、drop、takeRight和dropRight这些字符串函数是做什么用的? 和 substring相比,它们的优点和缺点都有哪些?
take、drop:从左边保留、去除n个字符
takeRight和dropRight:从右边保留、去除n个字符
和substring相比,它们的有点是更为简单直观,缺点是灵活性较substring欠缺。因为substring可以指定起始下标和终止下标(不包括)来获取子字符串。
def take(n: Int): String
Selects first n elements.
def takeRight(n: Int): String
Selects last n elements.
def drop(n: Int): String
Selects all elements except first n ones.
def dropRight(n: Int): String
Selects all elements except last n ones.
def substring(start: Int, end: Int): String
def substring(start: Int): String