zoukankan      html  css  js  c++  java
  • Scala学习笔记(五):内建控制循环

    前言

    Scala中内建控制循环包括if、while、for、try、match和函数调用。
    if和while与java类似,不做介绍。

    for

    基础用法

      def main(args: Array[String]): Unit = {
        val intArr = Array(1, 2, 3)
        for (i <- intArr) {
          println(i)
        }
      }
    

    过滤

    for语句块中可以添加if判断,用来达到过滤元素的效果

        for(i <- 1 to 20 if i % 3 == 0) {
          println(i)
        }
    

    if可以多次使用

        for (i <- 1 to 20 if i % 3 == 0 if i % 2 != 0) {
          println(i)
        }
    

    生成新集合

    使用yield,会记住每一次迭代,并最终收集生成新集合

        val inclusive = (1 to 20).toList
        val ints: List[Int] = for (i <- inclusive if i % 3 == 0 if i % 2 != 0) yield i
        println(ints)
    

    使用try表达式处理异常

    抛出异常

        try{
          val f = new FileReader("input.txt")
        } catch {
          case ex: FileNotFoundException => // 丢失文件异常
          case ex: IOException => // IO异常
        }
    

    match

      val firstArg = if (args.length > 0) args(0) else ""
      firstArg match {
        case "hello" => println("hello")
        case "world" => println("world")
        case _ => println("Hello World!")
      }
    

    match还可以产生值

      val firstArg = if (args.length > 0) args(0) else ""
      val friend = firstArg match {
        case "hello" => "Hello"
        case "world" => "World"
        case _ => "Hello World!"
      }
      println(friend)
    
  • 相关阅读:
    Oracle 函数
    ecplise 修改编码
    mysql json 使用 类型 查询 函数
    java 子类强转父类 父类强转子类
    java UUID
    Java Number & Math 类
    java String类
    apache StringUtils 工具类
    apache ArrayUtils 工具类
    java Properties
  • 原文地址:https://www.cnblogs.com/yw0219/p/10091240.html
Copyright © 2011-2022 走看看