scala基础之控制结构

来源:互联网 发布:mac 打开隐藏文件 编辑:程序博客网 时间:2024/06/04 20:15

在scala中IF表达式和while & do while循环和c,java是一样的,并没有什么不同。主要不同在于for循环和try catch语句块等

一for循环

1.1 使用关键字to

/**
 * to
会遍历到该值,而不是该值-1,这样的话下标从0开始,就会下标越界
 *
@param seq
 */
def forTo(seq:List[String]): Unit ={
    if (seq == Nil) {
        return;
    }
    for (x <- 0 to (seq.size- 1) ){
        print(seq(x)+" ")
    }
}

 

1.2 使用关键字until

/** * until 会遍历到下标为给定值 -1 ,不会有下标越界的问题 * @param seq */def forUntil(seq:List[String]): Unit ={    if (seq == Nil) {        return;    }    for (x <- 0 until seq.size){        print(seq(x)+" ")    }}

 

1.3 增强for循环

/** * 增强for循环 * @param seq */def forEnhance(seq:List[String]): Unit ={    if (seq == Nil) {        return;    }    println()    for (element <- seq){        print(element+" ")    }}

 

1.4 foreach

/** * 更加高级的for 循环,这样口可以节省代码行数,相当于是一个语法糖吧 * @param seq */def foreach(seq:List[String]) : Unit = {    if (seq == Nil) {        return;    }    println()    seq.foreach(element => print(element+" "))}

 

1.5 forall

/** * forall遍历每一个元素看是否满足指定的条件, * 如条件全部满足,返回TRUE否则返回FALSE * * @param seq */def forAll(seq:List[String]) : Unit = {    if (seq == Nil) {        return;    }    println()    val result = seq.forall(element => element.startsWith("h"))    println(result)}

 

二 for ……yield 操作

def forYield(): Unit ={    val ids = scala.collection.mutable.Set(1,2,3,
       4,5)    val newSet = for (e <- ids) yield  Math.pow(e,2)    newSet.toList.sorted.foreach(e => print(e+" "))}

 

三 switch 结构

Scala中switch结构和java 和 c不一样

3.1 基础的匹配

def switch(x:Int): Unit = {    Math.abs(xmatch {        case 0 => println("false")        case 1 => println("true")        //whoa表示默认情况下        case whoa => println("true")    }}

3.2 多个条件的匹配

def switchMultiCondition(x:Int): Unit = {    Math.abs(xmatch {        case 3|4|5 => println("spring")        case 6|7|8 => println("summer")        case 9|10|11 => println("autumn")        case 12|1|2 => println("winter")    }}

3.3 匹配结果赋给一个变量,前提是有返回值

def switchMultiCondition(x:Int): Unit = {    val result = Math.abs(xmatch {        case 3|4|5 => "spring"        case 6|7|8 => "summer"        case 9|10|11 => "autumn"        case 12|1|2 => "winter"    }    print(result)}

 

3.4 访问匹配表达式的缺省默认值

def switch(x:Int): Unit = {    Math.abs(xmatch {        case 0 => println("false")        case 1 => println("true")        //whoa表示默认情况下给的变量名,你可以在后面的语句块中直接使用它        case whoa => println("you provided value is: " +whoa+", so show true" )    }}

3.5 模式匹配

在匹配表达式中可以使用一种或者多种匹配模式,可以是常量模式,可以是变量模式,构造函数函数模式,序列模式或者元组或者类型模式

def echoWhatYouGiveMe(x:Any):String = x match {    /*常量模式*/    case 0 => "zero"    case true => "true"    case Nil => "an empty list"    /*序列模式*/    case List(0,_,_) => "A three-elements list with 0 as the first element"    case List(1,_*) => "A List begining with 1,having any number of elements"    case Vector(1,_*) => "A vector starting with 1,having any number of elements"    /*元组模式*/    case (a,b) => s"got $a and $b "    case (a,b,c) => s"got $a and $b and $c "    /*类型模式*/    case s:String => s"you gave me this string is: $s"    case i:Int => s"you gave me this int is: $i"    case f:Float => s"you gave me this float is: $f"    case a:Array[Double] => s"An array of double:${a.mkString(":")}"    case list:List[_] => s"thanks for the List: $list"    case map:Map[_,_] => map.toString    /*默认值,其余情况*/    case _ => "unknown"}

 

3.6 匹配表达式使用case类

trait Animals {    case class Dog(name:String) extends  Animals    case class Cat(name:String) extends  Animals    case object Woodpecker extends Animals    object ClassTest extends App{        def determineType(x:Animals):String = x match {            case Dog(moniker) => "Got a dog, name is "+moniker            case _:Cat => "Got a cat(igonre the name)"            case Woodpecker => "That was a Woodpecker"            case _ => "That was something else"        }        println(determineType(new Dog("Rocky")))        println(determineType(new Cat("Miao")))        println(determineType(Woodpecker))    }}

 

3.7 给case语句添加if语句

/** * 通过if 提供一个区间,然后匹配传递的值是否属于某一个区间 * @param x */def caseIfGuard(x:Int): Unit = {    x match {        case a if 0 to 9 contains(a) => println("0-9 range: "+a)        case b if 10 to 19 contains(b) => println("10-19 range: " + b)        case c if 20 to 29 contains(c) => println("20-29 range: " + c)        case _ => println("unknown range")    }}

 

3.8 使用匹配表达式替换isInstanceOf

def replaceIsInstanceOf(x:Any): Boolean ={    /*传统的判断一个类型*/    if (x.isInstanceOf[List]){        true    }    /*使用match case 去判断*/    x match {        case x:Set => true        case _ => false    }}

 

3.9 匹配表达式中使用List

def sum(list: List[Int]):Int = list match {    case Nil => 1    case x::rest => x+sum(rest)}

 

四 try {} catch{}

在try catch块中可以捕获一个或者多个异常

def trycatch_1(): Unit ={    val s = "foods"    try {        val i = s.toInt    } catch {        case e:Exception => e.printStackTrace()    }}/** * 可以捕获具体的异常 * 也可以同时捕获多个异常 */def trycatch_2(): Unit ={    val s = "foods"    try {        openFile("D:/a.txt")    } catch {        case e:FileNotFoundException => e.printStackTrace()        case e:IOException => e.printStackTrace()    }}

 

/** * 我们可以不用关心具体的异常 */def trycatch_3(): Unit ={    val s = "foods"    try {        openFile("D:/a.txt")    } catch {        case t:Throwable => t.printStackTrace()    }}

 

五 自定义控制结构

我们可以自定义控制结构,需要先定义一个函数,函数需要传入一个判断条件表达式和代码块

object Whilst {    def whilst(condition: => Boolean)(codeBlock: => Unit) {        if (condition) {            codeBlock            whilst(condition)(codeBlock)        }    }    def main(args: Array[String]) {        var i = 0;        whilst(i < 5) {            i = i+1;            println(i)        }    }}

 

原创粉丝点击