scala编程实战笔记(3-控制结构)

import scala.io.Source
    val source = Source.fromFile("/root/IdeaProjects/ScalaProgAction/src/test/scala/allrepl.scala").getLines()
    var count = 0
    for (line <- source) {
      //println(line)
      for (char <- line) {
        //println(char)
        if (char == 'f') count += 1  // "":String , '':Char
      }
    }
    println(count)

3.1for and foreach

  • for 的返回值
val arr: Array[String] = Array("dede", "dede", "sssa")
val newarr = for (w <- arr) yield w.capitalize
print(newarr.toList)
//yield 需要进一步的处理
var res =
for (a <- "asdc") yield {
var x = a.toByte + 1
x.toChar
}
  • 循环计数器
for (i <- 0 until arr.length) {
  println(s"$i : ${arr(i)}")
}
// zipWithIndex   
for ((e, count) <- arr.zipWithIndex) {
  println(e, count)
}
  • 生成器和卫语句
for (i <- 1 to 10 if (i % 2) == 0) {
  println(i)
}
  • 3.2 多个计数器 多个卫语句
for (i <- 1 to 3; j <- 1 to 3 if i == j) println(i, j)
for {
  i <- 1 to 3
  j <- 1 to 3
  if i == j
  if i > 2
} println(i, j)

3. 4 for yield

一般不会改变返回值类型

3.5 break continue

//break
import scala.util.control.Breaks._
breakable {
  for (i <- 1 to 10) {
    if (i >3) break
    println(i)
  }
}
//continue
for (i <- 1 to 10) {
  breakable {
    if (i % 2 == 1) break
    println(i)
  }
}
  • 多重嵌套break continue
import scala.util.control.Breaks
val outer = new Breaks
val inner = new Breaks
outer.breakable {
  // break
  for (i <- 1 to 10) {
    inner.breakable {
      // break continue
      for (j <- 'a' to  'e') {
        if (i == 1 && j == 'c') inner.break else println(i, j)
        if (i == 3 && j == 'c') outer.break
      }
    }
  }
 }

你可能感兴趣的:(scala编程实战笔记(3-控制结构))