大数据之scala(一) --- 安装scala,简单语法介绍,条件表达式,输入和输出,循环,函数,过程,lazy ,异常,数组

一、安装和运行Scala解释程序
---------------------------------------------
    1.下载scala-2.11.7.msi

    2.管理员运行--安装

    3.进入scala/bin,找到scala.bat,管理员运行,进入scala命令行


二、REPL
-----------------------------------------------------
    Read + Evaluate + Print + Loop


三、Scala的简单语法介绍
----------------------------------------------
    1.可以直接运行表达式
        //打印一个数组
        scala> 1 to 10
        res1: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    2.变量和常量
        val : value常量,赋值之后是不能改变的
        var : 变量,可以随意赋值和更改

        scala> val a = 100;
        scala> var b = 100;
        scala>  b = 200;

    3.scala也是有类型的,但是可以不写,使用var代替
        scala>  var a = "hello world";
        scala>  var a:String  = "hello world";
        a: String = hello

    4.常用数据类型
       a.Byte  Char  Short  Int  Long  Float  Double

       b.跟java不同,这些基本数据类型都是类

       c.可以对数字执行方法
        scala> 1.toString();
        res2: String = 1

        scala> 1.to(10);
        res3: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    5.操作符 + - * / % 的重载
        a. a 方法 b == a.方法(b);
            scala> 1.+(2)
            res5: Int = 3
            scala> 1 + 2
            res6: Int = 3

            scala> 1.to(10)
            res7: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
            scala> 1 to 10
            res8: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

        b.scala中并没有 ++ -- ,请使用 +=1 -=1

    6.调用函数和方法
        a.scala函数是没有对象的,但是方法是有对象的,方法是通过对象进行调用的
            最值函数: min(1,2),不需要依赖任何对象,直接可使用
            操作符重载方法: 1.+(2)  1 + 2  这是方法,需要对象调用

        b.scala中没有静态方法,但是scala有单例对象

        c.不带参数的scala方法,通常不使用圆括号
            scala> 1.toString()     //带括号
            scala> 1.toString       //不带括号
            scala> 1 toString       //运算符的方式

    7.导包
        scala> import scala.math._      //_ ===> *

    8.apply方法
         scala> "hello".apply(1)        //apply:,应用。取出第几个元素
         res1: Char = e

         scala> "hello"(1)              //apply的简写方式
         res2: Char = e

    9.Any是所有类型的超类,相当于java中的object

    10.类型转换
        scala> 1.toString
        res3: String = 1

        scala> "1000".toInt
        res4: Int = 1000

    11.空值Unit -- scala的表达式都有值,赋值表达式返回的是空值Unit,表现为(),类似于java中的void
        scala> val a = (s=3)
        a: Unit = ()

        scala> val y = ()
        y: Unit = ()

        scala> val y:Unit = ()
        y: Unit = ()

    12.:help查看帮助



四、条件表达式
-------------------------------------------------------------
    1.if -- else
        scala> val s = if(x > 0) 1 else -1
        等价于 scala> if(x > 0) s = 1 else s = -1

    2.块语句声明符{} : 表示本行语句尚未结束,相当于换行
        a.如果想换行,那么换行之前的语句就表示结束了。那么else if 就不知道是啥了。这种情况就需要使用大括号,告知大括号所在行尚未结束
            //表示两个表达式
            scala> if(x > 0) 1
            scala> else if (x == 0) 0 else -1

            //表示一个表达式
            scala> if(x > 0) { 1
            } else if (x == 0) 0 else -1

    3.paste模式
        :paste      // 进入粘贴模式,这个时候无论怎么换行, 都不会结束语句
        ctrl + D    //退出粘贴模式,开始计算粘贴模式中的内容
            scala> :paste
            // Entering paste mode (ctrl-D to finish)

            if (2 > 1)
             1
            else
             2

            // Exiting paste mode, now interpreting.

            res10: Int = 1


五、输入和输出函数
-----------------------------------------------------------
    a.print / println
        scala> print ("answer: ")
        answer:
        scala> print ("answer: " + 42 )
        answer: 42
        scala> println(42)
        42

    b.printf(占位符 %s %d %f)
        scala> printf("hello,%s! You are %d years old.\n", "tom" , 43)
        hello,tom! You are 43 years old.

    c.readLine[readInt readDouble readByte readShort ReadBoolean...]
         scala> val name = readLine("your name :")
         your name :name: String = tom

         scala> val age = readInt()
         age: Int = 15

         scala> printf("hello,%s! You are %d years old.\n", name , age)
         hello,tom! You are 15 years old.


六、循环
------------------------------------------------------------
    1.while循环
       scala> var n = 5;
       n: Int = 5

       scala> while(n > 0){
            | print("hello");
            | n -= 1;
            | }
       hellohellohellohellohello

    2.while循环打印99乘法表
        scala> var i = 1;
        i: Int = 1

        scala> :paste
        // Entering paste mode (ctrl-D to finish)

            while(i <= 9){

                var j = 1;
                while( j <= i)  {


                    printf("%d x %d = %d\t",j,i,(j*i));
                    print("  ");

                    j += 1;

                }
                println();
                i += 1;

            }

        // Exiting paste mode, now interpreting.

        1*1=1
        1*2=2  2*2=4
        1*3=3  2*3=6  3*3=9
        1*4=4  2*4=8  3*4=12  4*4=16
        1*5=5  2*5=10  3*5=15  4*5=20  5*5=25
        1*6=6  2*6=12  3*6=18  4*6=24  5*6=30  6*6=36
        1*7=7  2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49
        1*8=8  2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64
        1*9=9  2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81


    3.外部命令加载文件,执行99乘法表
        a.新建文件 D:\share\scala\workspace\99.scala

        b.粘贴内容
            var i = 1;
            while(i <= 9){
                var j = 1;
                while( j <= i)  {
                    printf("%d x %d = %d\t",j,i,(j*i));
                    print("  ");

                    j += 1;
                }
                println();
                i += 1;
            }

        c.使用load命令加载
           scala> :load D:\share\scala\workspace\99.scala
           Loading D:\share\scala\workspace\99.scala...
           i: Int = 1
           1 x 1 = 1
           1 x 2 = 2         2 x 2 = 4
           1 x 3 = 3         2 x 3 = 6       3 x 3 = 9
           1 x 4 = 4         2 x 4 = 8       3 x 4 = 12      4 x 4 = 16
           1 x 5 = 5         2 x 5 = 10      3 x 5 = 15      4 x 5 = 20      5 x 5 = 25
           1 x 6 = 6         2 x 6 = 12      3 x 6 = 18      4 x 6 = 24      5 x 6 = 30      6 x 6 = 36
           1 x 7 = 7         2 x 7 = 14      3 x 7 = 21      4 x 7 = 28      5 x 7 = 35      6 x 7 = 42      7 x 7 = 49
           1 x 8 = 8         2 x 8 = 16      3 x 8 = 24      4 x 8 = 32      5 x 8 = 40      6 x 8 = 48      7 x 8 = 56      8 x 8 = 64
           1 x 9 = 9         2 x 9 = 18      3 x 9 = 27      4 x 9 = 36      5 x 9 = 45      6 x 9 = 54      7 x 9 = 63      8 x 9 = 72      9 x 9 = 81

    4.百钱买百鸡
        公鸡:5块/只
        母鸡:3块/只
        小鸡:1块/3只

        var gong = 0;
        while(gong <= 20 )
        {
            var mu = 0;
            while(mu <= 33)
            {
                var xiao = 0;
                while(xiao < 100)
                {
                    if( gong * 5 + mu * 3 + xiao/3 == 100 && gong + mu + xiao == 100)
                    {
                        printf(gong,mu,xiao);
                    }
                    xiao += 3;
                }
                mu += 1;
            }
            gong += 1;
        }

        Loading D:\share\scala\workspace\100.scala...
        gong: Int = 0
        0_25_75
        4_18_78
        8_11_81
        12_4_84

    5.for循环
        a. to: 闭区间,将 1 到 10 轮流赋值给x
          scala> for(x <- 1 to 10){
               |     print(x + "\t");
               | }
          1       2       3       4       5       6       7       8       9       10

        b. until :左闭右开区间,将1 到 9 轮流赋值给x
            scala> for (x <- 1 until 10)
                 | {
                 |     print(x + "\t");
                 | }
            1       2       3       4       5       6       7       8       9

    6.scale没有break,也没有continue
        a.可以使用boolean变量进行控制

        b.使用嵌套函数 -- 可以从函数中return

        c.使用Breaks对象的break方法
            import scala.util.control.Breaks._
            breakable{
                for(...){
                    if(...) break;      //退出breakable块
                }
            }

            breakable{
                for(x <- 1 to 10)
                {
                    print(x);
                    break;
                }
            }

    7.高级for循环
        a.多个 <- ,用分号分割
            scala> for( i <- 1 to 3; j <- 1 to 3) print (( i + ":" + j) + "\t")
            //--   1:1     1:2     1:3     2:1     2:2     2:3     3:1     3:2     3:3

        b.多个 <- ,用分号分割,每个 <- 添加独立的判断
            scala> for( i <- 1 to 3 if i != 2; j <- 1 to 3) print (( i + ":" + j) + "\t")
            //--   1:1     1:2     1:3     3:1     3:2     3:3

            scala> for( i <- 1 to 3 if i != 2; j <- 1 to 3 if j != i) print (( i + ":" + j) + "\t")
            //--   1:2     1:3     3:1     3:2

        c.<- 过程中,可以定义任意多个变量,使用分号分割
            scala> for( i <- 1 to 3 if i != 2; kk=i-1 ; j <- kk to 3 if j != i) print (( i + ":" + j) + "\t")
            //--   1:0     1:2     1:3     3:2

        d.yield,是循环中处理每个元素,产生新集合
            scala> for (x <- 1 to 10 ) yield x % 2 ;
            res12: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 0, 1, 0, 1, 0, 1, 0, 1, 0)


七、函数
----------------------------------------------------------------------
    1.定义函数
        def fac(n : Int) = {
            var r = 1
            for(i <- 1 to n) r = r * i
            r
        }

        def add(a:Int,b:Int) : Int = {
            var c = a + b;
            return c;
        }

        def add(a:Int,b:Int) = {
           var c = a + b;
           c;
        }

    2.参数和返回值
        scala的函数,你必须给出所有的参数以及类型,但是不必须指定返回值和返回类型
        默认执行语句的之后一个表达式的值就是返回值

    3.scala实现递归 4! = 4 * 3 ![递归函数必须显示定义返回值类型]
        def func(n : Int):Int = {
            if(n != 1)
                return n * func(n-1);
            else
                return 1;
        }

    4.参数的默认值和带名参数
        def func2(head:String = "[", str:String = "tom" , tail:String = "]") = {
            head + str + tail;
        }

        scala> func2()
        res23: String = [tom]

        scala> func2("11","22");
        res21: String = 1122]

        scala> func2(str = "222");
        res22: String = [222]

    5.变长参数(Int*) 和 序列参数( :_* )
        [sum]:求和
        def sum(args : Int*) = {
            var sum = 0;
            for( arg <- args )   sum += arg;
            sum;
        }

        scala> sum(10)
        res24: Int = 10

        scala> sum(10,9,8,7,6)
        res25: Int = 40

        scala> sum(1 to 10:_*)      //注意,不能直接使用1 to 10,是错误的,要加上 :_*
        res26: Int = 55

        [reSum]:递归求和
        def reSum(args : Int*) : Int = {
            if(args.length == 0) return 0;
            else return args.head + reSum(args.tail:_*);
        }

        scala> reSum(1 to 10 :_*)
        res29: Int = 55


八、过程
-------------------------------------------------------------------------
    1.过程 -- 无返回值的函数的一种特殊表示方法
        函数体包含在花括号当中,但是没有前面的 = 号。返回类型是Unit

    2.过程不返回值,调用它仅仅是为了辅助作用,比如辅助打印一些符号和格式

    3.语句
        def out(a : Int) {
            println("***" + a + "***");
        }

        scala> out(22)
        ***22***


九、懒值lazy -- 延迟计算
-------------------------------------------------------------------------
    1.当val被声明为lazy的时候,它的初始化将被推迟,直到我们首次调用
        //直到访问words常量,才去打开文件,读取文件内容成字符串
        scala> lazy val words = scala.io.Source.fromFile("d:\\calllog.log").mkString
        words: String = <lazy>

        scala> print(words);
        15811111111,15032295555,2018/06/01 04:44:33,201
        18022222222,15732641111,2018/02/07 18:01:36,297
        17731086666,18301581111,2018/02/13 03:17:41,133
        18332561111,13341101111,2018/06/12 11:07:55,304
        13341101111,18301581111,2018/03/26 05:06:58,210
        18641241111,15733218888,2018/03/02 07:21:17,235
        13341101111,15614209999,2018/10/12 11:12:12,303
        15778421111,15614209999,2018/01/05 02:44:58,134
        18620191111,18332561111,2018/02/27 20:45:59,499
        18301581111,13269364444,2018/06/01 15:13:22,345
        15614209999,17731086666,2018/07/08 23:45:45,236
        18332561111,13269364444,2018/04/17 19:08:46,583
        15338597777,15732641111,2018/08/21 13:37:39,506
        15032295555,13269364444,2018/01/05 10:11:19,294
        15032295555,13560191111,2018/08/04 16:51:30,260
        13341101111,18301581111,2018/09/09 02:15:13,265
        13269364444,15733218888,2018/08/21 09:10:57,067


十、异常
-------------------------------------------------------------
    1. => 交给
        try{
          "hello".toInt;
        }
        catch{
            //交给
            case _:Exception                => print("xxxx") ;
            case ex:java.io.IOException     => print(ex)
        }

    2. _
        a.引入包的时候,表示统配,相当于*
        b.1 to 10 :_*   ,转成序列
        c.case _:Exception    => print("xxxx") ;

十一、数组
-----------------------------------------------------------------
    1.定长数组
        //10个整数的数组,默认所有元素的初始值是0
        val nums = new Array[Int](10);
        //已提供初始值,不需要new ,不需要类型,靠推断
        val s = Array("Hello","world")

    2.访问数组的元素
        //新建数组
        scala> val s = Array("Hello","world")
        //取值
        scala> print(s(0))
        //-- Hello
        //赋值
        scala> s(0) = "tom"
        scala> print(s(0))
        //-- tom

    3.变长数组 -- 数组缓冲 -- ArrayBuffer[java::ArrayList]
        //导包
        import scala.collection.mutable.ArrayBuffer
        //新建可变数组
        val b = ArrayBuffer[Int]()
        //尾端添加一个元素
        b += 1
        //尾端添加多个元素
        b += (1,2,3,4)
        //尾端添加新的可变集合
        b ++= Array(6,7,8)
        //移除尾端5个元素
        b.trimEnd(5)
        //移除开始的2个元素
        b.trimStart(2)
        //插入一个[效率不高]
        b.insert(2,6)
        //插入多个[效率不高] -- 第二的位置插入6 7 8
        b.insert(2,6,7,8)
        //移除指定位置的元素
        b.remove(2)
        //移除指定位置的多个元素 -- 从第二个位置开始移除,移除3个元素
        b.remove(2,3)

    4.遍历数组
        a.普通for
            for( i <- 0 until b.length) println(i + ":" + b(i))

        b.foreach
            for( i <- b) println(i)

    5.数组转换
        a.不修改原来数组,产生新的数组
            val a = Array(2,3,4,5)
            val res = for(e <- a) yield 2 * a   //含有yield的表达式,每次迭代对应一个

        b.过滤
            val a = Array(1 to 10:_*)           //产生数组
            a.filter(_ % 2 == 0).map(_ * 2)     //filter过滤器; _ 通配; map映射,相当于yield

    6.数组常用方法
        scala> arr.sum
        scala> arr.min
        scala> arr.max

    7.排序
        scala> import scala.util.Sorting._
        scala> val arr = Array(1,4,3,2)
        scala> quickSort(arr)            //arr有序

        val b = ArrayBuffer(1,7,2,9)
        val bSorted = b.sorted(_ < _)   //b没有被改变;bSorted是ArrayBuffer
        val bSorted = b.sorted(_ > _)   //b没有被改变;bSorted是ArrayBuffer

    8.数组toString
        scala> arr.mkString("<<",",",">>")  //<<1,2,3,4>>

    9.多维数组
        a.新建二维数组
            var arr = new Array[Array[Int]](4)
            var arr = Array.ofDim[Int](3,4)         //Int 类型  3行 4列

        b.赋值
            arr(0) = Array(1)
            arr(1) = Array(1,2)
            arr(2) = Array(1,2,3)
            arr(3) = Array(1,2,3,4)

            arr(row)(column) = 42            //给row行column列赋值

        c.遍历二维数组
            for(x <- arr){
                for(y <- x){
                    print(y)
                }
                println()
            }




























猜你喜欢

转载自blog.csdn.net/xcvbxv01/article/details/83450076
今日推荐