Scala process control

Branch control if else

Let the program execute selectively. There are three kinds of branch control: single branch, double branch and multi branch

1. Single branch

Basic grammar

if  (Conditional expression)  { 
 Execute code block 
} 

Description: when the conditional expression is true, the code of {} will be executed.

2. Double branch

Basic grammar

if (Conditional expression) { 
 Execute code block 1 
} else { 
Execute code block 2 
} 

3. Multi branch

Basic grammar

if (Conditional expression 1) { 
 Execute code block 1 
} 
else if (Conditional expression 2) { 
 Execute code block 2
 } 
   ...... 
else { 
 Execute code block n 
} 

4. Nested branches

Another complete branch structure is completely nested in one branch structure, and the branch structure inside is called the inner layer.
The branch structure outside the branch is called the outer branch. Nested branches should not exceed 3 levels.

Basic grammar

if(){ 
    if(){ 
 
    }else{ 
     } 
} 

Case practice

package chapter04

import scala.io.StdIn

object Test01_IfElse {
  def main(args: Array[String]): Unit = {
    println("Please enter your age:")
    val age: Int = StdIn.readInt()

    // 1. Single branch
    if (age >= 18){
      println("adult")
    }

    println("===================")

    // 2. Double branch
    if (age >= 18){
      println("adult")
    } else {
      println("under age")
    }

    println("===================")

    // 3. Multi branch
    if (age <= 6){
      println("childhood")
    } else if(age < 18){
      println("teenagers")
    } else if(age < 35){
      println("youth")
    } else if(age < 60){
      println("middle age")
    } else {
      println("old age")
    }
    println("===================")

    // 4. Return value of branch statement
    val result: Any = if (age <= 6){ //The return value is a public parent class
      println("childhood")
      "childhood"
    } else if(age < 18){
      println("teenagers")
      "teenagers"
    } else if(age < 35){
      println("youth")
      age
    } else if(age < 60){
      println("middle age")
      age
    } else {
      println("old age")
      age

    }
    println("result: " + result)

    // Ternary operator string res = (age > = 18) in java? "Adult": "minor"

    val res: String = if (age >= 18){
      "adult"
    } else {
      "under age"
    }

    val res2 = if (age >= 18) "adult" else "under age"

    println("===================")

    // 5. Nested branches
    if (age >= 18){
      println("adult")
      if (age >= 35){
        if (age >= 60){
          println("old age")
        } else {
          println("middle age")
        }
      } else {
        println("youth")
      }
    } else {
      println("under age")
      if (age <= 6){
        println("childhood")
      } else {
        println("teenagers")
      }
    }
  }
}

Switch branch structure

In Scala, there is no Switch, but pattern matching.

For cycle control

Scala also provides many features for the common control structure of the for loop. These features of the for loop are called
Is a for derivation or a for expression.

Range data cycle (To)

Basic grammar

for(i <- 1 to 3){ 
    print(i + " ") 
} 
println() 

(1) i represents the variable of the loop, < - specify to
(2) i will cycle from 1-3 and close back and forth

1. Range data cycle (Until)

Basic grammar

for(i <- 1 until 3) { 
    print(i + " ") 
} 
println() 

(1) The difference between this method and the previous one is that i is from 1 to 3-1
(2) Even if the front is closed and the rear is open

2. Cycle guard

Basic grammar

for(i <- 1 to 3 if i != 2) { 
    print(i + " ") 
} 
println() 

(1) Circular guard, i.e. circular protection type (also known as conditional judgment type, guard). If the protected type is true, the loop is entered
In the body, if false, skip, similar to continue.
(2) The above code is equivalent

for (i <- 1 to 3){ 
 if (i != 2) { 
 print(i + " ") 
 } 
} 

3. Cycle step

Basic grammar

for (i <- 1 to 10 by 2) { 
    println("i=" + i) 
} 

Note: by indicates the step size

4. Nested loop

Basic grammar

for(i <- 1 to 3; j <- 1 to 3) { 
    println(" i =" + i + " j = " + j) 
} 

Note: there is no keyword, so it must be added after the range; To block logic
The above code is equivalent

for (i <- 1 to 3) { 
    for (j <- 1 to 3) { 
        println("i =" + i + " j=" + j) 
    } 
} 

5. Introduce variables

Basic grammar

for(i <- 1 to 3; j = 4 - i) { 
    println("i=" + i + " j=" + j) 
} 

(1) When there are multiple expressions in a row of the for derivation, it should be added; To block logic
(2) The for derivation has an unwritten Convention: use parentheses when the for derivation contains only a single expression,
When multiple expressions are included, there is usually one expression per line, and curly braces are used instead of parentheses, as shown below

for { 
    i <- 1 to 3 
j = 4 - i 
} { 
    println("i=" + i + " j=" + j) 
} 

6. Loop return value

Basic grammar

val res = for(i <- 1 to 10) yield i 
println(res) 

Description: return the results processed during traversal to a new Vector collection, and use the yield keyword.
Note: it is rarely used in development.

Case practice

package chapter04

import scala.collection.immutable

object Test02_ForLoop {
  def main(args: Array[String]): Unit = {


    // 1. Range traversal
    for (i <- 1 to 10){  //Excluding 10
      println(i + ". hello world")
    }
    for (i: Int <- 1.to(10)){
      println(i + ". hello world")
    }

    println("===========================")
//    For (I < - range (1, 10)) {/ / excluding 10
//      println(i + ". hello world")
//    }
    for (i <- 1 until 10){  //Excluding 10
      println(i + ". hello world")
    }

    println("==============================")
    // 2. Set traversal
    for (i <- Array(12, 34, 53)){
      println(i)
    }
    for (i <- List(12, 34, 53)){
      println(i)
    }
    for (i <- Set(12, 34, 53)){
      println(i)
    }

    println("==========================")

    // 3. Cycle guard
    for (i <- 1 to 10){
      if (i != 5){
        println(i)
      }
    }

    for (i <- 1 to 10 if i != 5){  //Cycle guard
      println(i)
    }

    println("======================")

    // 4. Cycle step
    for (i <- 1 to 10 by 2){
      println(i)
    }
    println("-------------------")
    for (i <- 13 to 30 by 3){
      println(i)
    }

    println("-------------------")
    for (i <- 30 to 13 by -2){
      println(i)
    }
    for (i <- 10 to 1 by -1){
      println(i)
    }
    println("-------------------")
    for (i <- 1 to 10 reverse){
      println(i)
    }
    println("-------------------")
//    for (i <- 30 to 13 by 0){
//      println(i)
//    }/ / error, step cannot be 0

    for (data <- 1.0 to 10.0 by 0.3){
      println(data)
    }

    println("======================")

    // 5. Loop nesting
    for (i <- 1 to 3){
      for (j <- 1 to 3){
        println("i = " + i + ", j = " + j)
      }
    }
    println("-------------------")
    for (i <- 1 to 4; j <- 1 to 5){
      println("i = " + i + ", j = " + j)
    }

    println("======================")

    // 6. Loop in variables
    for (i <- 1 to 10){
      val j = 10 - i
      println("i = " + i + ", j = " + j)
    }

    for (i <- 1 to 10; j = 10 - i){
      println("i = " + i + ", j = " + j)
    }

    for {
      i <- 1 to 10
      j = 10 - i
    }
    {
      println("i = " + i + ", j = " + j)
    }

    println("======================")

    // 7. Cycle return value
    val a = for (i <- 1 to 10) {
      i
    }
    println("a = " + a)

    val b: immutable.IndexedSeq[Int] = for (i <- 1 to 10) yield i * i
    println("b = " + b)
  }
}

While and do... While loop control

1.While cycle control

Basic grammar

Loop variable initialization 
while (Cycle condition) { 
 Circulatory body(sentence) 
 Cyclic variable iteration 
} 

(1) A loop condition is an expression that returns a Boolean value
(2) A while loop is a statement that is judged before execution
(3) Unlike the for statement, the while statement does not return a value, that is, the result of the entire while statement is of type Unit ()
(4) Because there is no return value in while, it is inevitable to use this statement to calculate and return the result
If the variable needs to be declared outside the while loop, it is equivalent to the internal to external variable of the loop
Therefore, it is not recommended to use the for loop instead.

2.do... while loop control

Basic grammar

 Loop variable initialization; 
 do{ 
  Circulatory body(sentence) 
 Cyclic variable iteration 
 } while(Cycle condition) 

(1) A loop condition is an expression that returns a Boolean value
(2) do... while loop is executed first and then judged

Case practice

package chapter04

object Test05_WhileLoop {
  def main(args: Array[String]): Unit = {
    // while
    var a: Int = 10
    while (a >= 1){
      println("this is a while loop: " + a)
      a -= 1
    }

    //do while
    var b: Int = 0
    do {
      println("this is a do-while loop: " + b)
      b -= 1
    } while (b > 0)
  }
}

Cycle interrupt

Basic description

Scala's built-in control structure specifically removes break and continue in order to better adapt to functional programming and push
It is recommended to use a functional style to solve the functions of break and continue, rather than a keyword. The breakable control structure is used in Scala to implement break and continue functions.

Case practice

package chapter04

import scala.util.control.Breaks
import scala.util.control.Breaks._

object Test06_Break {
  def main(args: Array[String]): Unit = {
    // 1. Exit the loop by throwing an exception
    try {
      for (i <- 0 until 5){
        if (i == 3)
          throw new RuntimeException
        println(i)
      }
    } catch {
      case e: Exception =>    // Do nothing, just exit the loop
    }

    // 2. Use the break method of the Breaks class in Scala to throw and catch exceptions
    Breaks.breakable(
      for (i <- 0 until 5){
        if (i == 3)
          Breaks.break()
        println(i)
      }
    )

    breakable(
      for (i <- 0 until 5){
        if (i == 3)
          break()
        println(i)
      }
    )

    println("This is code outside the loop")
  }
}

Multiple cycles

Basic description

(1) A nested loop is formed when one loop is placed in another loop. Where, for, while, do... While
Both can be used as outer cycle and inner cycle.
[it is recommended to use two layers in general and no more than three layers at most]
(2) Let the outer layer cycle times be m times and the inner layer cycle times be n times, then the inner layer cycle body actually needs to execute m*n times.

Case practice

package chapter04

// Output 99 multiplication table
object Test03_Practice_MulTable {
  def main(args: Array[String]): Unit = {
    for (i <- 1 to 9){
      for (j <- 1 to i){
        print(s"$j * $i = ${i * j} \t")
      }
      println()
    }

    // Abbreviation
    for (i <- 1 to 9; j <- 1 to i){
      print(s"$j * $i = ${i * j} \t")
      if (j == i) println()
    }
  }
}

Keywords: Scala

Added by tomharding on Wed, 12 Jan 2022 09:43:34 +0200