Scala学习笔记06【Tuple、Array、Map、文件实战入门】

1、Scala的Tuple入门示例程序:

object TupleTest 
{
  def main(args: Array[String]): Unit = 
  {
    val triple = (100, "Scala", "Spark", "难免有错")

    println(triple._1)   //编号从1开始!!!
    println(triple._2)
    println(triple._3)
    println(triple._4)
  }

}

运行结果:

100
Scala
Spark
难免有错

2、Scala的Array入门示例程序:

object ArrayTest 
{
  def main(args: Array[String]): Unit = 
  {
    val array = Array(1, 2, 3, 4, 5)

    //1较为繁琐的方法
    for(i <- 0 until array.length)
    {
      print(array(i) + " ")
    }

    println()
    //2效率更高的写法
    for(elem <- array)
    {
      print(elem + " ")
    }
  }
}

运行结果:

1  2  3  4  5  
1  2  3  4  5  

3、Scala的Map入门示例程序:

object MapTest 
{
  def main(args: Array[String])
  {
    val ages = Map("zhangsan" -> 23, "lisi" -> 34)

    for((k,v) <- ages)
    {
      println("Key: " + k + "\t Value: " + v)
    }


    //"_"占位符,表示这个值不想要,即只要key的值示例
    for((k,_) <- ages)
    {
      println("Key: " + k )
    }
  }
}

运行结果:

Key: zhangsan Value: 23
Key: lisi Value: 34
Key: zhangsan
Key: lisi

4、Scala的文件读取入门示例程序:

首先在C盘根目录创建文件Leslie.txt,内容为:
Chinese Name:zhang guorong
English Name: Leslie
dowhat?:Star

import scala.io.Source      //需要引入Source包

object FileTest 
{
  def main(args: Array[String])
  {
    println("本地文本按行读取:")
    val file = Source.fromFile("C:\\Leslie.txt")

    for(line <- file.getLines)  //按行读取
    {
      println(line)
    }

    println("\nURL文件按行读取:")
    val URLFile = Source.fromURL("https://www.baidu.com/")
    for(line <- URLFile.getLines)
    {
      println(line)
    }

  }
}

运行结果:

本地文本按行读取:
Chinese Name:zhang guorong
English Name: Leslie
dowhat?:Star

URL文件按行读取:
<html>
<head>
    <script> location.replace(location.href.replace("https://","http://")); </script>
</head>
<body>
    <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>

你可能感兴趣的:(scala,array,map,File,Tuple)