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

本文通过四个示例介绍了Scala编程的基本概念,包括使用Tuple进行数据组合、使用Array进行数据操作、使用Map进行键值对存储以及如何读取本地与远程文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值