博客
关于我
Scala_1.控制台打印,变量定义,函数定义
阅读量:317 次
发布时间:2019-03-04

本文共 2367 字,大约阅读时间需要 7 分钟。

Scala_1 控制台打印,变量定义,函数定义

Scala 是一款强大且灵活的编程语言,当我们开始学习 Scala 时,首先需要掌握的就是控制台打印、变量定义以及函数定义等基础知识。以下将通过实际代码示例,详细讲解这些概念的使用方法。

控制台打印

在 Scala 中,控制台打印可以通过 println 方法实现。与其他编程语言不同,Scala 的 println 方法可以直接用于打印字符串或其他数据类型。以下是一个简单的打印示例:

println("Hello World!")  println(10)

这段代码将在控制台输出:

Hello World!
10

变量定义

Scala 中变量的定义非常简单,主要有两种变量类型:valvar

  • val 用于定义不变量,值在声明时必须初始化。
  • var 用于定义可变变量,值可以在运行时改变。

以下是一个变量练习的示例:

val x = 10  var y = 10  y = 20  val z: Int = 10  val a: Double = 1.0  val b: Double = 10.0

这段代码将定义多个变量,并演示了如何为变量指定类型。

字符串操作

Scala 对字符串操作支持相当强大,可以通过多种方法来操作字符串。以下是一些常用的字符串操作示例:

// 使用交换字符串  println(s"We have $n apples")  // 数组操作  val c = Array(11, 9, 6)  println(s"My Second daughter is ${c(0)-c(2)} years old.")  // 数学运算  println(s"We have double the amount of ${n/2.0} in apples.")  println(s"Power of 2:${math.pow(2,2)}")  // 格式化字符串  println(f"Power of 5:${math.pow(5,2)}%1.0f")  println(f"Square of 122:${math.sqrt(122)}%1.4f")  // 原始字符串  println(raw"New line feed:\n.Carriage return:\r.")

函数定义

在 Scala 中,函数定义非常简单,主要有两种函数定义方式:defobject。以下是一个函数练习的示例:

object HelloWorld {   def main(args: Array[String]): Unit = {     // 打印输出     printStr()     variablePractice()     strOperation()     println(functionName(12, 5))   }   // 打印练习   def printStr(): Unit = {     println("Hello World!")     println(10)     print("Hello World!")   }   // 变量练习   def variablePractice(): Unit = {     val x = 10     var y = 10     y = 20     val z: Int = 10     val a: Double = 1.0     val b: Double = 10.0     println("Hello World".length)     println("Hello World".substring(2, 6))     println("Hello World".replace("H", "3"))     println("Hello World".take(5))     // Hello     println("Hello World".drop(5))     // World   }   // 字符串操作   def strOperation(): Unit = {     // s""     val n = 45     println(s"We have $n apples")     // f""     val c = Array(11, 9, 6)     println(f"My Second daughter is ${c(0)-c(2)} years old.")     // raw""     println(raw"New line feed:\n.Carriage return:\r.")     // 正常字符串     println("They stood outside the \"Rose and Crown\"")     // HTML 字符串     val html = """       

Press belo',Joe

""" println(html) } // 函数练习 def functionName(a: Int, b: Int): Int = { // 可以添加更多操作 return a + b } }

通过以上代码示例,我们可以清晰地看到 Scala 在控制台打印、变量定义、字符串操作以及函数定义方面的特点和优势。

转载地址:http://ysnq.baihongyu.com/

你可能感兴趣的文章
node模块化
查看>>
node模块的本质
查看>>
node环境下使用import引入外部文件出错
查看>>
node环境:Error listen EADDRINUSE :::3000
查看>>
Node的Web应用框架Express的简介与搭建HelloWorld
查看>>
Node第一天
查看>>
node编译程序内存溢出
查看>>
Node读取并输出txt文件内容
查看>>
node防xss攻击插件
查看>>
noi 1996 登山
查看>>
noi 7827 质数的和与积
查看>>
NOI-1.3-11-计算浮点数相除的余数
查看>>
noi.ac #36 模拟
查看>>
NOI2010 海拔(平面图最大流)
查看>>
NOIp2005 过河
查看>>
NOIP2011T1 数字反转
查看>>
NOIP2014 提高组 Day2——寻找道路
查看>>
noip借教室 题解
查看>>
NOIP模拟测试19
查看>>
NOIp模拟赛二十九
查看>>