Scala learning (variables and data types, process control)

Variables and Data Types

note

package learn02
object demo01 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    //单行注释
    /*
    多行注释
     */
    /**
     * 文档注释
     */
  }
}

variable

package learn02
object demo02 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val name//错误,必须显示进行初始化操作
    val name: String = "xwk" //不可变变量
    name = "stefan" //错误,值不可改变
    var age: Int = 21 //可变变量
    age = 22
    age = "abc" //错误,值可以改变,类型不可变
  }
}

string

package learn02
object demo03 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val name : String="xwk"
    //字符串连接
    println("hello "+name)
    //传值字符串(格式化字符串)
    printf("my name is %s\n",name)
    //插值字符串
    println(s"my name is ${
      
      name}")
    //多行字符串
    println(
      s"""
         |Hello
         | ${
      
      name}
         |""".stripMargin
    )
  }
}

input Output

package learn02
import java.io.{
    
    File, PrintWriter}
object demo04 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    //标准化屏幕输入
    println("请输入您的年龄:")
    val age:Int=scala.io.StdIn.readInt()
    println("您的年龄为:"+age)

    //从文件中获取输入
    scala.io.Source.fromFile("./src/learn02/users.txt").foreach(
      line=>{
    
    
        print(line)
      }
    )
    scala.io.Source.fromFile("./src/learn02/users.txt").getLines()

    //输出,文件写操作
    val writer=new PrintWriter(new File("./src/learn02/test.txt"))
    writer.write("Hello Scala")
    writer.close()
  }
}

When Scala interacts with network data, it uses the I/O class in java to
run first demo05_TestServerand then run demo05_TestClient, and then demo05_TestServerdisplay the output content, just end the program.

package learn02
import java.io.{
    
    BufferedReader, InputStreamReader}
import java.net.{
    
    ServerSocket, Socket}
object demo05_TestServer {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val server=new ServerSocket(9999)
    while(true){
    
    
      val socket:Socket=server.accept()
      val reader=new BufferedReader(
        new InputStreamReader(
          socket.getInputStream,
          "UTF-8"
        )
      )
      var s:String=""
      var flg=true
      while(flg){
    
    
        s=reader.readLine()
        if(s!=null){
    
    
          println(s)
        }else{
    
    
          flg=false
        }
      }
    }
  }
}
package learn02
import java.io.{
    
    OutputStreamWriter, PrintWriter}
import java.net.Socket
object demo05_TestClient {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val client=new Socket("localhost",9999)
    val out=new PrintWriter(
      new OutputStreamWriter(
        client.getOutputStream,
        "UTF-8"
      )
    )
    out.print("Hello Scala")
    out.flush()
    out.close()
    client.close()
  }
}

type of data

insert image description here
As can be seen from the figure, Any is the supertype of all types, also known as the top-level type, which contains two direct subclasses, as follows: 1.AnyVal:
represents the value type, and the data described by the value type is a non-empty value, not an object. It predefines 9 types, namely Double, Float, Long, Int, Short, Byte, Unit, Char and Boolean. Among them, Unit is a value type that does not represent any meaning, and its function is similar to void in Java.
2. AnyRef: Indicates the reference type. It can be considered that, except value types, all types inherit from AnyRef.

​At the bottom of the Scala data type hierarchy, there are two more data types, namely Nothing and Null. The details are as follows:
1. Nothing: the subtype of all types, also known as the bottom type. Its common use is to signal termination, such as throwing an exception, program exit, or an infinite loop.
2. Null: All subtypes of reference types, its main purpose is to interoperate with other JVM languages, and it is hardly used in Scala code.

type conversion

package learn02
object demo06 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    //自动类型转化(隐式转换)
    val b:Byte=10
    val s:Short=b
    val i:Int=s
    val lon:Long=i
    println(lon)

    //强制类型转化
    /*
    java语言
    int a=10
    byte b=(byte)a
     */
    var n1:Int=10
    var n2:Byte=n1.toByte

    //字符串类型转化
    var n3:Long=10
    println("num "+n3)
    n3.toString//scala是完全面向对象的语言,所有的类型都提供了toString方法,可以直接转换为字符串
    println("num "+n3)//任意类型都提供了和字符串进行拼接的方法
  }
}

identifier

Scala 可以使用两种形式的标志符,字符数字和符号。
	字符数字使用字母或是下划线开头,后面可以接字母或是数字,符号"$"在 Scala 中也看作为字母。然而以"$"开头的标识符为保留的 Scala 编译器产生的标志符使用,应用程序应该避免使用"$"开始的标识符,以免造成冲突。
	Scala 的命名规范采用和 Java 类似的 camel 命名规范,首字符小写,比如 toString。类名的首字符还是使用大写。此外也应该避免使用以下划线结尾的标志符以避免冲突。

process control

branch control

package learn02
object demo07_if {
    
    
  def main(args: Array[String]): Unit = {
    
    
    var age=10
    //单分支
    if(age==10){
    
    
      println("yes")
    }
    //双分支
    age=15
    if(age==10){
    
    
      println("yes")
    }else{
    
    
      println("no")
    }
    //多分支
    age=25
    if(age<18){
    
    
      println("童年")
    }else if(age<=30){
    
    
      println("青年")
    }else if(age<=50){
    
    
      println("中年")
    }else {
    
    
      println("老年")
    }
  }
}

cycle control

for

package learn02
object demo07_for {
    
    
  def main(args: Array[String]): Unit = {
    
    
    for (i <- Range(1, 5)) {
    
    //范围集合,1-4
      print(i + " ")
    }
    println()
    for (i <- 1 to 5) {
    
     //包含5
      print(i + " ")
    }
    println()
    for (i <- 1 until 5) {
    
     //不包含5
      print(i + " ")
    }
    println()
    //循环守卫
    for(i <- Range(1,5) if i !=3){
    
    
      print(i+" ")
    }
    println()
    //循环步长
    for(i <- Range(1,5,2)){
    
    
      print(i+" ")
    }
    println()
    for(i <- 1 to 5 by 2){
    
    
      print(i+" ")
    }
    println()
    //循环嵌套
    for(i <- Range(1,5);j<- Range(1,4)){
    
    
      print("i="+i+",j="+j+" ")
    }
    println()
    for(i <- Range(1,5)){
    
    
      for(j <- Range(1,4)){
    
    
        print("i="+i+",j="+j+" ")
      }
    }
    println()
    //引入变量
    for(i <- Range(1,5);j=i-1){
    
    
      print("j="+j+" ")
    }
    println()
    //循环返回值
    val result=for(i <- Range(1,5))yield {
    
    
      i*2
    }
    print(result)
  }
}

while

package learn02
object demo07_while {
    
    
  def main(args: Array[String]): Unit = {
    
    
    var i=0
    while(i<5){
    
    
      print(i+" ")
      i+=1
    }
    println()
    var j=5
    do{
    
    
      print(j+" ")//5
    }while(j<5)
  }
}

loop break

package learn02
object demo07_zd {
    
    
  def main(args: Array[String]): Unit = {
    
    
    scala.util.control.Breaks.breakable{
    
    
      for(i <- 1 to 5){
    
    
        if(i==3){
    
    
          scala.util.control.Breaks.break
        }
        print(i+" ")//1 2
      }
    }
  }
}

Guess you like

Origin blog.csdn.net/weixin_46322367/article/details/125215695