1. If statement, the whole is the same as C++, I write something that you may not be familiar with.
object HelloWorld {
def main(args: Array[String]) {
var x = 2
println(if(x > 0) 1 else -1)
var s = if(x > 0) 1 else -1
println(s)
//甚至用混合类型的
var a = if(x > 0) "abc" else -1
println(a)
//如果else部分缺失,不能直接空
if(x > 0) 1 else ()
}
}
2. Termination statement
Single-line multiple statements: var x = 1; x = x+1 needs to add one;
multiple-line single statement: var x = 1+
2 Here we end with the operator +
3. Block expressions, expressions in {}
import scala.math.sqrt
object HelloWorld {
def main(args: Array[String]) {
var x = {
var a = 100; sqrt(a)}//只会等于最后一个
println(x)
}
}
4. Input and output
Input: You can use readLine, readBoolean, readInt, etc. to input the corresponding type. But only readLine has a prompt string.
import scala.io.StdIn.readLine
object HelloWorld {
def main(args: Array[String]) {
var x = readLine("please in")
println(x)
}
}
Output: print() and println(), note that ln is added to wrap. (You can also use c-style output printf)
import scala.io.StdIn.{
readInt, readLine}
object HelloWorld {
def main(args: Array[String]) {
var x = readInt()
printf("x is %d",x)
}
}
5. Loops, while and do loops are the same as
for loops in previous languages
object HelloWorld {
def main(args: Array[String]) {
val s = "hello"
var sum = 0
for(i <- 0 until s.length)
sum += s(i)
println(sum)
}
}
Enhanced for loop
object HelloWorld {
def main(args: Array[String]) {
for(i<- 1 to 3; j<- 1 to 3) println(10*i+j)
}
}