zoukankan      html  css  js  c++  java
  • scala 基本语法

    /**
       * 测试  for 循环
       */
      def testFor(){
        for(i <- 1 to 10){
          println("number is :"+i)
          
        }
      for(i <- 1 to 2; j <- 1 to 2) print(i*100 + j+"   ") 
      for(i <- 1 to 2; j <- 1 to 2 if i != j) print(i*100 + j+"   ")
    }

    2.测试增强 for 循环

     /**
       * 测试增强 for 循环
       */
      def testFor2(){
        var files = new java.io.File("D:/").listFiles()
        for(file <- files){
    //      println(file)
        }
      }

    3.测试 if

      /**
       * 测试   if
       */
      def testIf(){
        def file = ""
        def str = if(file != "") file else "b.txt" 
          print(str)
      }

    4.

      /**
       * 测试  Tuple (元组)
       */
      def tuple(){
        val  pair = (100, "scala", "spark")
        println(pair._1+" "+pair._2+" "+pair._3)
      }

    5. 测试 map

      /**
       * 测试  map
       */
      def testMap(){
        val tMap = Map("scala" -> 20, "spark" -> 30)
        print(tMap.getOrElse("scala", 0))   获取 key 为 scala 的值,  如果没有值,   则设置默认值为 0
        for((k, v) <- tMap){
          println("key is:" +k +"  value is:"+v)
        }
        
        //循环 key
        for((k,_) <- tMap){
          println("key is:"+k)
        }
        //循环 value
        for((_,v) <- tMap){
          println("value is:"+v)
        }
      }

    6. 测试 数组

      /**
       * 测试  数组
       */
      def testArray(){
        val array = Array(1,2,3,4,5)
        for(i <- 0 until array.length){
          print(array(i))
        }
        println()
        
        for(tem <- array){
          print(tem)
          
        }
        println()
      }

    7. scala 读取文件

      /**
       * scala 读取文件
       */
      def testFile(){
       val file = Source.fromFile("D:/a.txt")
    // val file = Source.fromURL("http://www.youku.com")
    for(line <- file.getLines()){ println(line) } }

    8.  函数

    def addA(x: Int) = x + 100
    
    //匿名函数
    
          var add = (x:Int) => x+200
          print(add(2))

    9. 递归函数

          def fac(n:Int):Int = if(n <= 0) 1 else n*fac(n-1)
          println(fac(10))

    10.  有参函数

    def combine(content:String, left:String, right:String) = left+content+right
          println(combine("test", "[","]"))
        
        def combine(content:String, left:String="[", right:String="]") = left+content+right
        println(combine("test"))

     10.  数组

        val arr = new Array[Int](10)              //> arr  : Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
          arr(0) = 1
          for(ar <- arr) print(ar)                  //> 1000000000
          
          val nums = new Array[Int](10)             //> nums  : Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
        nums(0) = 1
        for(num <- nums) print(num)                   //> 1000000000
        
        val strs = new Array[String](10)              //> strs  : Array[String] = Array(null, null, null, null, null, null, null, null
                                                      //| , null, null)
        strs(1) = "spark"
        strs(2) = "scala"
        strs                                          //> res0: Array[String] = Array(null, spark, scala, null, null, null, null, null
                                                      //| , null, null)
        for(str <- strs) print(str)                   //> nullsparkscalanullnullnullnullnullnullnull
        
        val arrs = Array(1,2,3,4)                     //> arrs  : Array[Int] = Array(1, 2, 3, 4)
        for(arr <- arrs) print(arr)                   //> 1234
        
        val b = ArrayBuffer[Int]()                    //> b  : scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
        b+=1                                          //> res1: com.test.Test4.b.type = ArrayBuffer(1)
             b+=(2,3)                          //> res2: com.test.Test4.b.type = ArrayBuffer(1, 2, 3)
             b++=Array(4,5,6)                  //> res3: com.test.Test4.b.type = ArrayBuffer(1, 2, 3, 4, 5, 6)
             
             b.insert(1,8,9)  //向下标为 1 的位置插入 8, 9
             b                                 //> res4: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 8, 9, 2, 3,
                                                      //|  4, 5, 6)
             
             b.remove(1,2)
             b                                 //> res5: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5,
                                                      //|  6)
             b.toArray                         //> res6: Array[Int] = Array(1, 2, 3, 4, 5, 6)
             
             
             val c = Array(1,6,3,4,5)          //> c  : Array[Int] = Array(1, 6, 3, 4, 5)
             val result = for(c1 <- c) yield 10*c1   //使用  yield 将会使结果 产生一个新的数组
                                                      //> result  : Array[Int] = Array(10, 60, 30, 40, 50)
             result                            //> res7: Array[Int] = Array(10, 60, 30, 40, 50)
             
             var result2 = for(c1 <-c if c1%2==0) yield 10*c1   //for中可以含有 if 条件语句
                                                      //> result2  : Array[Int] = Array(60, 40)
             
             val d = c.filter(_%2 == 0).map(10*_)   //一般使用这个方法来进行过滤和计算
                                                      //> d  : Array[Int] = Array(60, 40)
             d.sum                             //> res8: Int = 100
             d.sorted     //排序                 //> res9: Array[Int] = Array(40, 60)
             
             
             val f = Array(2,3,1,98,3)         //> f  : Array[Int] = Array(2, 3, 1, 98, 3)
             scala.util.Sorting.quickSort(f)  //快排
             f                                 //> res10: Array[Int] = Array(1, 2, 3, 3, 98)
             
             f.mkString(" and ")   //以   and  来链接所有元素
                                                      //> res11: String = 1 and 2 and 3 and 3 and 98
             
             f.mkString("{", ",", "}")   //对元素左侧增加 {   右侧增加}  , 中间以 , 号隔开
                                                      //> res12: String = {1,2,3,3,98}
             f                                 //> res13: Array[Int] = Array(1, 2, 3, 3, 98)
             
             //二维数组
             val matrix = Array.ofDim[Double](3, 4)
                                                      //> matrix  : Array[Array[Double]] = Array(Array(0.0, 0.0, 0.0, 0.0), Array(0.0
                                                      //| , 0.0, 0.0, 0.0), Array(0.0, 0.0, 0.0, 0.0))
             matrix(2)(1) = 55
             matrix                            //> res14: Array[Array[Double]] = Array(Array(0.0, 0.0, 0.0, 0.0), Array(0.0, 0
                                                      //| .0, 0.0, 0.0), Array(0.0, 55.0, 0.0, 0.0))
    View Code

    11.  元祖

    var tup = (1,2,33,4,5)  
    val (a,b,_,_,_) = tup    //每个元素对应元祖中的每个元素, 没有定义的可以使用_ 占位符来一一对应
    print(a+b)

    12. partition   来判断元素是否否和某个特性,  结果会将是和否的分开放到一个集合中

        val np = "Rocky Spark".partition(_.isUpper)
          print(np)          //结果为: (RS,ocky park)

    13, zip 的使用,   2个数组中相同下标构成新的元素,  拉链操作

    val symbols = Array("[", "-", "]")
    val count = Array(2,5,2)
    val sy = symbols.zip(count)
    for((x,y) <- sy) Console.print(x+y)   //结果: [2-5]2   交替相加
    println()
    for((x,y) <- sy) Console.print(x*y)   //结果: [[-----]]   以 count 个数展示 symbols

    14. scala 中 类的使用

    class People(){  //scala 中会自动生成 get set 方法,
        private var age1 = 30     //生成private 类型的 get set 方法
        var age2 = 20         //生成 public 类型的 get set 方法
    }

    def main(args: Array[String]): Unit = {
       
    var people = new People
      // print(people.age1)
       print(people.age2)

    }
  • 相关阅读:
    【leetcode】9. Palindrome Number
    【leetcode】7. Reverse Integer
    【Leetcode】6. ZigZag Conversion
    Mysql读写分离
    Windows下为PHP安装redis扩展
    jquery 写的图片左右连续滚动
    PHP中spl_autoload_register函数的用法
    MySQL命令行查询乱码解决方法:
    AJAX 教程
    Mac安装composer爬过的坑
  • 原文地址:https://www.cnblogs.com/redhat0019/p/9284538.html
Copyright © 2011-2022 走看看