Scala学习笔记05【Scala函数定义、流程控制、异常入门】

Scala函数定义及流程控制:

可运行完整代码示例:

object ScalaFucBasic 
{
  def main(args: Array[String]): Unit =   //Unit代表函数返回值为空,即void
  {
    println("----函数使用示例----") //分号可要可不要

    println("Scala流程控制之dowhile循环:")
    dowhile        //调用函数dowhile(),也可以用dowhile(),“()”可要可不要

    println("\n参数传递函数looper()结果:")
    println(looper(100, 298) + "\n")

     //Scala流程控制之判断
    println("\nScala流程控制之判断:")

    var fileName1 = "Scala.txt"
    if(fileName1 != "" ) 
      println(fileName1) 
    else println("AAAAA")       //输出为Scala.txt

    var fileName2 = ""
    if(fileName2 !="") 
      println(fileName2) 
    else println("AAAAA")      //输出为AAAAA

    //for循环
    println("\nfor循环:")
    for(i <- 1 to 5)          //从1到5
      println("Number is: " + i)

    println("\n当前目录下文件:" )
    var files = (new java.io.File(".")).listFiles() //获取文件列表
    for(file <- files)   //循环输出各文件名字
    {
      print(file + "\t")
    }
  }

  //dowhile循环示例
  def dowhile()
  {
    var line = ""

    do
    {
      println("Please input something:")
      line = readLine()    //控制台输入
      println(line)

    }while(line != "") //输入为空时跳出循环

  }


  //带参数的函数定义
  def looper(x: Long, y: Long): Long = 
  {
    var a = x
    var b = y

    while(a != 0)
    {
      val temp = a
      a = b % a
      b = temp
    }
    b  //返回值为b的Long型数值
  }
}

运行结果:

----函数示例----
Scala流程控制之dowhile循环:
Please input something:
201510071607
201510071607
Please input something:



参数传递函数looper()结果:
2


Scala流程控制之判断:
Scala.txt
AAAAA

for循环:
Number is: 1
Number is: 2
Number is: 3
Number is: 4
Number is: 5

当前目录下文件:
.\.cache-main   .\.classpath    .\.project  .\.settings .\bin   .\src   

Scala异常入门示例:

代码示例:

object ScalaExceptionTest 
{
  def main(args: Array[String]): Unit =
  {
    val n = 99
    try
    {
      val half = 
        if(n % 2 == 0) 
          n / 2 
        else 
          throw new RuntimeException("n必须为偶数!")

    }catch
    {
      case e: Exception => println("异常信息:" + e.getMessage())

    }finally
    {
      //do sth.
    }
  } 
}

运行结果:

异常信息:n必须为偶数!

你可能感兴趣的:(scala,函数,流程控制,异常)