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 需要進(jìn)一步的處理
var res =
for (a <- "asdc") yield {
var x = a.toByte + 1
x.toChar
}
- 循環(huán)計(jì)數(shù)器
for (i <- 0 until arr.length) {
println(s"$i : ${arr(i)}")
}
// zipWithIndex
for ((e, count) <- arr.zipWithIndex) {
println(e, count)
}
- 生成器和衛(wèi)語(yǔ)句
for (i <- 1 to 10 if (i % 2) == 0) {
println(i)
}
- 3.2 多個(gè)計(jì)數(shù)器 多個(gè)衛(wèi)語(yǔ)句
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
一般不會(huì)改變返回值類型
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
}
}
}
}