scala for while

scala> :paste
// Entering paste mode (ctrl-D to finish)

val n = 10
for(i <- 1 to 10)
print(i)

// Exiting paste mode, now interpreting.

12345678910n: Int = 10
scala> :paste
// Entering paste mode (ctrl-D to finish)
val str = "hello word"
for(c <- str)print(c + "  ")
// Exiting paste mode, now interpreting.

h  e  l  l  o     w  o  r  d  str: String = hello word

 

加強for循環scala

高級for循環

scala> :paste
// Entering paste mode (ctrl-D to finish)

for(i <- 1 to 9; j <- 1 to 9){
    if(j == 9){
        println(i*j)
    }else{
        print(i*j + "  ")
    }
}


// Exiting paste mode, now interpreting.

1  2  3  4  5  6  7  8  9
2  4  6  8  10  12  14  16  18
3  6  9  12  15  18  21  24  27
4  8  12  16  20  24  28  32  36
5  10  15  20  25  30  35  40  45
6  12  18  24  30  36  42  48  54
7  14  21  28  35  42  49  56  63
8  16  24  32  40  48  56  64  72
9  18  27  36  45  54  63  72  81
scala> :paste
// Entering paste mode (ctrl-D to finish)

/** if守衛 **/
for(i <- 1 to 20 if i%2 == 0) print(i + " ")

// Exiting paste mode, now interpreting.

2 4 6 8 10 12 14 16 18 20
/** for推倒式,構建集合 **/
scala> for(i <- 1 to 10)yield i
res17: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
相關文章
相關標籤/搜索