// 2.1 条件表达式
val x = 2
val s = if (x > 0) 1 else -1
if (x > 0) "positive" else -1
// 返回值类型不一致,无法确定返回值的类型,所以返回Any类型
// 2.2 语句终止
var n = 2
var r = 0
if (n > 0) {r = r * n; n -= 1 }
if (n > 0) {
r = r * n
n -= 1
}
// 2.3 块表达式和赋值
// 在scalak ,{}块包含一系列表达式,其结果也是一个表达式。块中最后一个表达式的值就是块的值
// 这个特性对于那种对某个val的初始化需要分多步完成的情况很有用
import scala.math.sqrt
val distance = { val dx = x - 1; val dy = x - 2;sqrt(dx * dx + dy * dy) }
// 2.4 输入和输出
print("Answer: ") // 不换行
println(22) // 换行
println("Answer: "+ 22)
printf("Hello,%s! You are %d years old.\n","CC",1) // 格式化打印
val name = readLine("Your name: ")
print("Your age: ")
val age = readInt()
printf("Hello, %s! Next year, your will be %d.\n",name, age + 1)
// 循环
while (n > 0) {
r = r * n
n -= 1
}
var result1 = 1
for ( i <- 1 to 22) {
result1 = result1 * i
}
val str1 = "Hello "
var sum = 0
for (i <- 0 until str1.length){
sum += str1(i)
}
var sum1 = 0
for(ch <- "Hello") {sum1 += ch}
// 2.6 高级for循环和for推导式
for(i <- 1 to 3; j <- 1 to 3) {print((10 * i + j) + " ")}
for(i <- 1 to 3; j <- 1 to 3 if i != j){print((10 * i + j) + " ")}
for(i <- 1 to 10) yield i % 3 // Vector(1, 2, 0, 1, 2, 0, 1, 2, 0, 1)
for(c <- "Hello"; i <- 0 to 1) yield (c + i).toChar
for(i <- 0 to 1; c <- "Hello") yield (c + i).toChar
// 2.7 函数
def abs(x: Double) = if(x >= 0) x else -x
def fac(n: Int) = {
var r = 1
for (i <- 1 to n) {
r = r * i
}
r
}