package com.zhu.scala
import java.io.{File, FileNotFoundException, FileReader}
/**
* Created by zhuhailong-dc on 2017/3/3.
*
* 内建控制结构
* 1. if
* 2. while
* 3. For
* 4. Try
* 5. Match
* 6. break&continue
*
*/
class Scala_5{
}
object Scala_5 {
def main(args: Array[String]): Unit = {
//1. if
/**
* 在scala中使用val比var更好的体现面向函数式编程,同时也更好的支持了等效推论
*/
val filename = if (1 == 1) 1 else 0
//println(filename)
//2. while
var line = ""
// do{
// //line=readLine(); //在控制台输入内容
// println("Read:"+line)
// }while(line=="")
/**
* 在Scala中 一个方法中,没有返回值的话,等于() 这是不同于Java的地方
*/
//3. For
val files = (new File(".")).listFiles();
for (file <- files) {
//println(file)
}
for (i <- 1 to 4) {
//println(i)
}
for (i <- 1 until 4) {
//println(i)
}
for (file <- files if file.isFile; if file.getName.endsWith("main")) {
//println(file)
}
def fileLines(file: java.io.File) = scala.io.Source.fromFile(file).getLines().toList
// def grep(pattern: String) =
// for {
// file <- files if file.isFile
// line <- fileLines(file) if line.trim.matches(pattern)
// } println(file + ":::" + line.trim)
//
// grep(".*xml.*")
// def grep2(pattern:String)=
// for{
// file<-files if file.isFile
// line<-fileLines(file)
// trimmed=line.trim
// if trimmed.matches(pattern) //mid-stream(流间) 变量绑定 不需要使用val或者var声明
// } println(file+":::"+trimmed)
val forLineLengths=
for{
file<-files if file.isFile
line<-fileLines(file)
trimmed=line.trim
if trimmed.matches(".*project.*")
}yield trimmed
//forLineLengths.foreach(println)
// 4.Try
// try{
// val f=new FileReader("bbbb")
// }catch{
// case ex: FileNotFoundException=> //handle missing file
// case ex: IOException=> //handle other I/O error
// }finally{
// println(1)
// }
// 5.match
val firstArg=if(1==21) "salt" else ""
firstArg match {
case "salt" => println("papper")
case "chips"=> println("salsa")
case _ => println("huh") //表示缺省状态
}
val friend=firstArg match {
case "salt" => "papper"
case "chips" => "salsa"
case _ => "huh"
}
//println("friend:"+friend)
// 6. break&continue
/**
* 在scala中没有break和continue的概念
*/
def searchFrom(i:Int):Int=
if(i>=args.length) -1
else if (args(i).startsWith("-")) searchFrom(i+1)
else if (args(i).endsWith(".scala")) i
else searchFrom(i+1)
var i=searchFrom(0)
println(i)
}
}
Scala控制结构讲解
最新推荐文章于 2025-07-12 10:39:13 发布