第二章
***内容概述
- if表达式也是有值的
val x = if(x>0) 1 else -1
- 块也有值-是它最后一个表达式
val value= { val x = 10 - 20 val y = 10 + 20 (x * y) } value = -300
- Sala的for循环就像是java“增强for”循环
for(x <- 0 to 10){ print(x) }
- 分号(大多数情况下不是必须的)
- void类型是Unit
- 避免在函数表达是中使用return
这位大佬记载了为什么 https://blog.csdn.net/wang_wbq/article/details/80231895 - 异常工作方式和java中的基本一样,不同的是你在catch语句中使用的“模式匹配”
- Scala中没有受检异常
***习题
-
如果一个数字为正数,则它的signum为1;如果是负数,则signum为-1;如果是0,则signum是0, 编写一个函数来计算这个值
def problem_1(num: Int): Int = { if (num > 0) 1 else if (num == 0) 0 else -1 }
-
一个空的块表达式的值是什么?它的类型是什么
值是(),类型是Unit
-
指出Scala何种情况下赋值语句x=y=1是合法的
在x的类型为Unit的情况下是合法的
-
针对下列java循环编写一个scala版
//答案一 def problem_4(): Unit = { var i = 10 while (i >= 0) { println(i) i = i - 1 } } //答案二 //def problem_4(): Unit = {for(x <- (0 to 10).reverse){println(x)}}
-
编写一个过程countdown(n:Int),打印从n到0的数字
def countdown(n: Int): Unit = { var i = n while (i >= 0) { println(i) i = i - 1 } }
-
编写一个for循环,计算字符串中所有字母的unicode代码的乘积 举例来说,"Hello"中所有字母的字符成为9415087488L
def problem_6(input: String): BigInt = { var sum: BigInt = 1 val length = input.length for (i <- 0 to length - 1) { sum = sum * input(i).toLong } sum }
-
同样是解决6的问题,但不能够用循环(提示,StringOps)
def problem_7(input: String): BigInt = { var sum: BigInt = 0 sum = input.map(_.toLong).product sum }
-
略
-
把前一个练习的函数改为递归函数
def problem_9(input: String, curIndex: Int): BigInt = { if (curIndex == input.length - 1) { input(curIndex).toLong } else { problem_9(input, curIndex + 1) * input(curIndex).toLong } }
-
编写函数计算x 的n次方
def problem_10(x: Double, n: Int): BigDecimal = {
if (n == 0) {
1
} else if (n < 0) {
1 / problem_10(x, -1 * n)
} else if (n % 2 == 1) {
x * problem_10(x, n - 1)
} else {
problem_10(x, n / 2) * problem_10(x, n / 2)
}
}