SCALA入门(2)

第二节,今天学习scala的函数定义,流程控制,异常处理

函数定义

package com.scala.study

object HelloScala {
    def main(args:Array[String]){
        doWhile
    }
    
    def doWhile(){
       var line = ""
       do{
         line = readLine()
         println("read:" + line)
       }while(line!="")
    }
}

有参数的函数

package com.scala.study

object HelloScala {
    def main(args:Array[String]){
        println(lopper(100,528))
    }
    
    def lopper(x:Long,y:Long):Long= {
      var a = x;
      var b = y;
      while(a!=0){
          var temp = a
          a = b%a
          b =temp
      }
      b
    }
}

条件控制

package com.scala.study

object HelloScala {
    def main(args:Array[String]){
       var file = "scala.txt";
       if(!args.isEmpty)file=args(0)
       println(file)
    }
    
}
package com.scala.study

object HelloScala {
    def main(args:Array[String]){
       var file1 = if(!args.isEmpty) args(0) else "scala.txt"
       println(file1)
    }
    
}

循环

package com.scala.study

object HelloScala {
    def main(args:Array[String]){
     for(i<-1 to 10)
       println(i)
    }
    
}
package com.scala.study
object HelloScala {
    def main(args:Array[String]){
     for(i<-1.to(10))
       println(i)
    }
}
package com.scala.study
object HelloScala {
    def main(args:Array[String]){
        var files = (new java.io.File(".").listFiles());
        for(file <- files){
          println(file)
        }
      
    }
}

scala异常

package com.scala.study
object HelloScala {
    def main(args:Array[String]){
      var n=99
      try{
        var half = if(n%2==0) n/2 else throw new RuntimeException("N must be event")
      }
      catch{
        case e: Exception => println(e.getMessage)
      }finally{
        
      }
      
    }
}

相关推荐