7. Scala process control

Posted by siwis on Tue, 01 Feb 2022 17:14:53 +0100

Process control

Branch control if else

  let the program execute selectively. There are three branches: single branch, double branch and multi branch

Single branch

  • Basic grammar
if (Conditional expression) {
	Execute code block
}

Note: when the conditional expression is true, the code of () will be executed.

  • case

Demand: enter the age of the person. If the age of the comrade is less than 18, then "minor" will be output

Double branch

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

Note: when the conditional expression is true, the code of () will be executed
When the conditional expression is false, else code is executed

  • case

Demand: enter the age of the person. If the age of the comrade is less than 18, then "minor" will be output; otherwise, "adult" will be output

Multi branch

  • Basic grammar
if (Conditional expression 1) {
	Execute code block
} else if (Conditional expression 2) {
	Execute code block
}else if (Conditional expression 3) {
	Execute code block
}
...
else if (Conditional expression n) {
	Execute code block
} else {
	Execute code block
}

Note: when the conditional expression is true, the code of () will be executed
When the conditional expression is false, else code is executed

  • case

Requirements:
Output "childhood" when age is less than or equal to 6
Output "minor" when the age is less than 18
Output "adult" when the age is less than 35
Output "middle age" when the age is less than 60
Otherwise, output "old age"

package day04

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("under age")
    } else if (age < 35) {
      println("adult")
    } else if (age < 60) {
      println("middle age")
    } else {
      println("old age")
    }
  }
}
Output result:
Please enter your age:
24
 adult
===============
adult
=============
adult

Return value of branch statement

package day04

import scala.io.StdIn

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

    // Return value of branch statement
    val result: String = if (age <= 6) {
      println("childhood")
      "childhood"
    } else if (age < 18) {
      println("under age")
      "under age"
    } else if (age < 35) {
      println("adult")
      "adult"
    } else if (age < 60) {
      println("middle age")
      "middle age"
    } else {
      println("old age")
      "old age"
    }
    println("result:" + result)
  }
}
Output result:
Please enter your age
24
 adult
result:adult
package day04

import scala.io.StdIn

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

    // Return value of branch statement
    val result1: String = if (age <= 6) {
      println("childhood")
      "childhood"
    } else if (age < 18) {
      println("under age")
      "under age"
    } else if (age < 35) {
      println("adult")
      "adult"
    } else if (age < 60) {
      println("middle age")
      "middle age"
    } else {
      println("old age")
      "old age"
    }
    println("result1:" + result1)
  }
}
Output result:
Please enter your age
24
 adult
result:()
package day04

import scala.io.StdIn

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

    // Return value of branch statement
    val result2: Any = if (age <= 6) {
      println("childhood")
      "childhood"
    } else if (age < 18) {
      println("under age")
      age
    } else if (age < 35) {
      println("adult")
      age
    } else if (age < 60) {
      println("middle age")
      age
    } else {
      println("old age")
      age
    }
    println("result2:" + result2)
  }
}
Output result:
Please enter your age
25
 adult
result2:25

Any can return any type of return value

Scala does not have ternary operators

package day04

import scala.io.StdIn

object Test01_IfElse {
  def main(args: Array[String]): Unit = {
    println("Please enter your age")
    val age: Int = StdIn.readInt()
    
    // Scala has no ternary operator string res2 = (age > = 18)? "Adult": "minor"
    val res: String = if (age >= 18) {
      "adult"
    } else {
      "under age"
    }
    println("res" + res)

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

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

    //    String res3 = (age >=18)?  "Adult": "minor"
  }
}
Output result:
Please enter your age
25
res adult
============
res2 adult

Nested statement

package day04

import scala.io.StdIn

object Test01_IfElse {
  def main(args: Array[String]): Unit = {
    println("Please enter your age:")
    val age: Int = StdIn.readInt()
    
    // 5. Nested branch
    if (age >= 18) {
      println("adult")
      if (age >= 35) {
        if (age >= 60) {
          println("old age")
        } else {
          println("middle age")
        }
      }
    } else {
      println("under age")
      if (age <= 6) {
        println("childhood")
      }
    }
  }
}
Output result:
Please enter your age:
23
 adult

For cycle control

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

Range data cycle (To)

  • Basic grammar
for (i < -1 to 3) {
	print(i + " ")
}
println()
  • i represents the variable of the loop, < - specify to

  • i will cycle from 1-3 and close back and forth

  • case

Demand: output 5 sentences of "pretty boy, you are so handsome!"

package day04

object Test02_ForLoop {
  def main(args: Array[String]): Unit = {
    // java for syntax: for (int i = 0; I < 5; I + +) {system. Out. Println (I + ". Hello world");}

    // Range traversal
    for (i <- 1 to 5) {
      println(i + ".Pretty boy, you are so handsome!")
    }

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

    for (i <- 6.to(10)) {
      println(i + ".Pretty boy, you are so handsome!")
    }

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

    for (i <- Range(1, 10)) {
      println(i + ".Pretty boy, you are so handsome!")
    }

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

    for (i <- 1 until (10)) {
      println(i + ".Pretty boy, you are so handsome!")
    }
  }
}
Output result:
G:\Java\jdk\bin\java.exe "-javaagent:F:\IDEA2021.3.1qiye\IntelliJ IDEA 2021.3.1\lib\idea_rt.jar=54760:F:\IDEA2021.3.1qiye\IntelliJ IDEA 2021.3.1\bin" -Dfile.encoding=UTF-8 -classpath G:\java\jdk\jre\lib\charsets.jar;G:\java\jdk\jre\lib\deploy.jar;G:\java\jdk\jre\lib\ext\access-bridge-64.jar;G:\java\jdk\jre\lib\ext\cldrdata.jar;G:\java\jdk\jre\lib\ext\dnsns.jar;G:\java\jdk\jre\lib\ext\jaccess.jar;G:\java\jdk\jre\lib\ext\jfxrt.jar;G:\java\jdk\jre\lib\ext\localedata.jar;G:\java\jdk\jre\lib\ext\nashorn.jar;G:\java\jdk\jre\lib\ext\sunec.jar;G:\java\jdk\jre\lib\ext\sunjce_provider.jar;G:\java\jdk\jre\lib\ext\sunmscapi.jar;G:\java\jdk\jre\lib\ext\sunpkcs11.jar;G:\java\jdk\jre\lib\ext\zipfs.jar;G:\java\jdk\jre\lib\javaws.jar;G:\java\jdk\jre\lib\jce.jar;G:\java\jdk\jre\lib\jfr.jar;G:\java\jdk\jre\lib\jfxswt.jar;G:\java\jdk\jre\lib\jsse.jar;G:\java\jdk\jre\lib\management-agent.jar;G:\java\jdk\jre\lib\plugin.jar;G:\java\jdk\jre\lib\resources.jar;G:\java\jdk\jre\lib\rt.jar;F:\IDEADEMO\ScalaLearnDemo\target\classes;G:\java\scala\scala-2.12.11\lib\scala-library.jar;G:\java\scala\scala-2.12.11\lib\scala-parser-combinators_2.12-1.0.7.jar;G:\java\scala\scala-2.12.11\lib\scala-reflect.jar;G:\java\scala\scala-2.12.11\lib\scala-swing_2.12-2.0.3.jar;G:\java\scala\scala-2.12.11\lib\scala-xml_2.12-1.0.6.jar day04.Test02_ForLoop
1.Pretty boy, you are so handsome!
2.Pretty boy, you are so handsome!
3.Pretty boy, you are so handsome!
4.Pretty boy, you are so handsome!
5.Pretty boy, you are so handsome!
===============
6.Pretty boy, you are so handsome!
7.Pretty boy, you are so handsome!
8.Pretty boy, you are so handsome!
9.Pretty boy, you are so handsome!
10.Pretty boy, you are so handsome!
===============
1.Pretty boy, you are so handsome!
2.Pretty boy, you are so handsome!
3.Pretty boy, you are so handsome!
4.Pretty boy, you are so handsome!
5.Pretty boy, you are so handsome!
6.Pretty boy, you are so handsome!
7.Pretty boy, you are so handsome!
8.Pretty boy, you are so handsome!
9.Pretty boy, you are so handsome!
===============
1.Pretty boy, you are so handsome!
2.Pretty boy, you are so handsome!
3.Pretty boy, you are so handsome!
4.Pretty boy, you are so handsome!
5.Pretty boy, you are so handsome!
6.Pretty boy, you are so handsome!
7.Pretty boy, you are so handsome!
8.Pretty boy, you are so handsome!
9.Pretty boy, you are so handsome!

Set traversal

package day04

object Test02_ForLoop {
  def main(args: Array[String]): Unit = {
    // 2. Set traversal
    for (i <- Array(12, 34, 56, 23)) {
      println(i)
    }
    for (i <- List(12, 34, 56, 23)) {
      println(i)
    }
    for (i <- Set(12, 34, 56, 23)) {
      println(i)
    }
  }
}

Operation results:
12
34
56
23
12
34
56
23
12
34
56
23

Cycle guard

  • Basic grammar
for (i <- 1 to 3 if i != 2) {
	println(i + " ")
}
  • Circular guard, i.e. circular protection mode (also known as conditional guard). If the protected type is true, it will enter the loop body, and if it is false, it will skip, which is similar to continue (not in Scala)

  • The above code is equivalent

for (i <- 1 to 3) {
if (1 != 2) {
	println(i + " ")
}
}
  • case
package day04

object Test02_ForLoop {
  def main(args: Array[String]): Unit = {
    // 3. Cycle guard
    for (i <- 1 to 10) {
      if (i != 5) {
        println(i)
      }
    }

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

    for (i <- 1 to 10 if i != 5) {
      println(i)
    }
  }
}
Output result:
1
2
3
4
6
7
8
9
10
===============
1
2
3
4
6
7
8
9
10

Cycle step

Step cannot be 0

package day04

object Test02_ForLoop {
  def main(args: Array[String]): Unit = {
    // 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)
    }
    println("===============")

    for (i <- 10 to 1 by -1) {
      println(i)
    }

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

    for (i <- 1 to 10 reverse) {
      println(i)
    }

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

    for (data <- 1.0 to 10.0 by 0.5) {
      println(data)
    }
  }
}
Output result:
1
3
5
7
9
===============
13
16
19
22
25
28
===============
30
28
26
24
22
20
18
16
14
===============
10
9
8
7
6
5
4
3
2
1
===============
10
9
8
7
6
5
4
3
2
1
===============
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
5.5
6.0
6.5
7.0
7.5
8.0
8.5
9.0
9.5
10.0

Nested loop

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

There is no keyword, so you must add it after the scope; To block logic

  • The above code is equivalent
for (i <- 1 to 3) {
	for (j <-1 to 3) {
		println("i = " + i + "j =" + j)
	}
}
  • case
package day04

object Test02_ForLoop {
  def main(args: Array[String]): Unit = {
    // 5. Loop nesting
    for (i <- 1 to 3) {
      for (j <- 1 to 3) {
        println("i = " + i + " j =" + j)
      }
    }

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

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

multiplication table

package day04

//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()
    }

    println("=========================")
    
    //Abbreviation
    for (i <- 1 to 9; j <- 1 to i) {
      print(s"$j * $i = ${i * j}\t")
      if (j == i) println()
    }
  }
}
Output result:
G:\Java\jdk\bin\java.exe "-javaagent:F:\IDEA2021.3.1qiye\IntelliJ IDEA 2021.3.1\lib\idea_rt.jar=55763:F:\IDEA2021.3.1qiye\IntelliJ IDEA 2021.3.1\bin" -Dfile.encoding=UTF-8 -classpath G:\java\jdk\jre\lib\charsets.jar;G:\java\jdk\jre\lib\deploy.jar;G:\java\jdk\jre\lib\ext\access-bridge-64.jar;G:\java\jdk\jre\lib\ext\cldrdata.jar;G:\java\jdk\jre\lib\ext\dnsns.jar;G:\java\jdk\jre\lib\ext\jaccess.jar;G:\java\jdk\jre\lib\ext\jfxrt.jar;G:\java\jdk\jre\lib\ext\localedata.jar;G:\java\jdk\jre\lib\ext\nashorn.jar;G:\java\jdk\jre\lib\ext\sunec.jar;G:\java\jdk\jre\lib\ext\sunjce_provider.jar;G:\java\jdk\jre\lib\ext\sunmscapi.jar;G:\java\jdk\jre\lib\ext\sunpkcs11.jar;G:\java\jdk\jre\lib\ext\zipfs.jar;G:\java\jdk\jre\lib\javaws.jar;G:\java\jdk\jre\lib\jce.jar;G:\java\jdk\jre\lib\jfr.jar;G:\java\jdk\jre\lib\jfxswt.jar;G:\java\jdk\jre\lib\jsse.jar;G:\java\jdk\jre\lib\management-agent.jar;G:\java\jdk\jre\lib\plugin.jar;G:\java\jdk\jre\lib\resources.jar;G:\java\jdk\jre\lib\rt.jar;F:\IDEADEMO\ScalaLearnDemo\target\classes;G:\java\scala\scala-2.12.11\lib\scala-library.jar;G:\java\scala\scala-2.12.11\lib\scala-parser-combinators_2.12-1.0.7.jar;G:\java\scala\scala-2.12.11\lib\scala-reflect.jar;G:\java\scala\scala-2.12.11\lib\scala-swing_2.12-2.0.3.jar;G:\java\scala\scala-2.12.11\lib\scala-xml_2.12-1.0.6.jar day04.Test03_Practice_MulTable
1 * 1 = 1	
1 * 2 = 2	2 * 2 = 4	
1 * 3 = 3	2 * 3 = 6	3 * 3 = 9	
1 * 4 = 4	2 * 4 = 8	3 * 4 = 12	4 * 4 = 16	
1 * 5 = 5	2 * 5 = 10	3 * 5 = 15	4 * 5 = 20	5 * 5 = 25	
1 * 6 = 6	2 * 6 = 12	3 * 6 = 18	4 * 6 = 24	5 * 6 = 30	6 * 6 = 36	
1 * 7 = 7	2 * 7 = 14	3 * 7 = 21	4 * 7 = 28	5 * 7 = 35	6 * 7 = 42	7 * 7 = 49	
1 * 8 = 8	2 * 8 = 16	3 * 8 = 24	4 * 8 = 32	5 * 8 = 40	6 * 8 = 48	7 * 8 = 56	8 * 8 = 64	
1 * 9 = 9	2 * 9 = 18	3 * 9 = 27	4 * 9 = 36	5 * 9 = 45	6 * 9 = 54	7 * 9 = 63	8 * 9 = 72	9 * 9 = 81	
1 * 1 = 1	
1 * 2 = 2	2 * 2 = 4	
1 * 3 = 3	2 * 3 = 6	3 * 3 = 9	
1 * 4 = 4	2 * 4 = 8	3 * 4 = 12	4 * 4 = 16	
1 * 5 = 5	2 * 5 = 10	3 * 5 = 15	4 * 5 = 20	5 * 5 = 25	
1 * 6 = 6	2 * 6 = 12	3 * 6 = 18	4 * 6 = 24	5 * 6 = 30	6 * 6 = 36	
1 * 7 = 7	2 * 7 = 14	3 * 7 = 21	4 * 7 = 28	5 * 7 = 35	6 * 7 = 42	7 * 7 = 49	
1 * 8 = 8	2 * 8 = 16	3 * 8 = 24	4 * 8 = 32	5 * 8 = 40	6 * 8 = 48	7 * 8 = 56	8 * 8 = 64	
1 * 9 = 9	2 * 9 = 18	3 * 9 = 27	4 * 9 = 36	5 * 9 = 45	6 * 9 = 54	7 * 9 = 63	8 * 9 = 72	9 * 9 = 81	

Introduce variables

  • Basic grammar
for (i <- 1 to 3;j = 4 - i) {
	println("i =" + i + " j =" + j)
}
  • When there are multiple expressions in a row of for derivation, it is necessary to add; To block logic
  • There is an unwritten Convention for the for derivation: when the for derivation contains only a single expression, parentheses are used. When multiple expressions are included, there is generally one expression per line, and curly braces are used instead of parentheses, as follows
for {
	i <- 1 to 3
	j = 4 - i
} {
	println("i =" + i + " j =" + j)
}
  • case
package day04

object Test02_ForLoop {
  def main(args: Array[String]): Unit = {
    // 5. Loop nesting
    for (i <- 1 to 3) {
      for (j <- 1 to 3) {
        println("i = " + i + " j =" + j)
      }
    }

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

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

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

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

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

    for (i <- 1 to 10; j = 10 - i) {
      println("i =" + i + " j =" + j)
    }
  }
}
Output result:
i =1 j =9
i =2 j =8
i =3 j =7
i =4 j =6
i =5 j =5
i =6 j =4
i =7 j =3
i =8 j =2
i =9 j =1
i =10 j =0
===============
i =1 j =9
i =2 j =8
i =3 j =7
i =4 j =6
i =5 j =5
i =6 j =4
i =7 j =3
i =8 j =2
i =9 j =1
i =10 j =0

Nine story demon tower

package day04

object Test_04Practice_Pyramid {
  def main(args: Array[String]): Unit = {
    for (i <- 1 to 9) {
      val stars = 2 * i -1
      val spaces = 9 - i
      println(" " * spaces + "*" * stars)
    }

    println("==========")
    for (i <- 1 to 9;stars = 2 * i;spaces = 9 -i) {
      println(" " * spaces + "*" * stars)
    }

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

    for (stars <- 1 to 17 by 2;spaces = (17 - stars) / 2) {
      println(" " * spaces + "*" * stars)
    }
  }
}
Output result:
G:\Java\jdk\bin\java.exe "-javaagent:F:\IDEA2021.3.1qiye\IntelliJ IDEA 2021.3.1\lib\idea_rt.jar=56097:F:\IDEA2021.3.1qiye\IntelliJ IDEA 2021.3.1\bin" -Dfile.encoding=UTF-8 -classpath G:\java\jdk\jre\lib\charsets.jar;G:\java\jdk\jre\lib\deploy.jar;G:\java\jdk\jre\lib\ext\access-bridge-64.jar;G:\java\jdk\jre\lib\ext\cldrdata.jar;G:\java\jdk\jre\lib\ext\dnsns.jar;G:\java\jdk\jre\lib\ext\jaccess.jar;G:\java\jdk\jre\lib\ext\jfxrt.jar;G:\java\jdk\jre\lib\ext\localedata.jar;G:\java\jdk\jre\lib\ext\nashorn.jar;G:\java\jdk\jre\lib\ext\sunec.jar;G:\java\jdk\jre\lib\ext\sunjce_provider.jar;G:\java\jdk\jre\lib\ext\sunmscapi.jar;G:\java\jdk\jre\lib\ext\sunpkcs11.jar;G:\java\jdk\jre\lib\ext\zipfs.jar;G:\java\jdk\jre\lib\javaws.jar;G:\java\jdk\jre\lib\jce.jar;G:\java\jdk\jre\lib\jfr.jar;G:\java\jdk\jre\lib\jfxswt.jar;G:\java\jdk\jre\lib\jsse.jar;G:\java\jdk\jre\lib\management-agent.jar;G:\java\jdk\jre\lib\plugin.jar;G:\java\jdk\jre\lib\resources.jar;G:\java\jdk\jre\lib\rt.jar;F:\IDEADEMO\ScalaLearnDemo\target\classes;G:\java\scala\scala-2.12.11\lib\scala-library.jar;G:\java\scala\scala-2.12.11\lib\scala-parser-combinators_2.12-1.0.7.jar;G:\java\scala\scala-2.12.11\lib\scala-reflect.jar;G:\java\scala\scala-2.12.11\lib\scala-swing_2.12-2.0.3.jar;G:\java\scala\scala-2.12.11\lib\scala-xml_2.12-1.0.6.jar day04.Test_04Practice_Pyramid
        *
       ***
      *****
     *******
    *********
   ***********
  *************
 ***************
*****************
==========
        **
       ****
      ******
     ********
    **********
   ************
  **************
 ****************
******************
==========
        *
       ***
      *****
     *******
    *********
   ***********
  *************
 ***************
*****************

Loop return value

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

Description: return the results processed in the traversal process to a new Vector set, and use the yield keyword.

Note: it is rarely used in development

  • case

Requirement: multiply all values in the original data by 2 and return the data to a new set.

package day04

object Test02_ForLoop {
  def main(args: Array[String]): Unit = {
    // 6. Loop return value
    val a: Unit = for (i <- 1 to 10) {
      i
    }
    println("a =" + a)

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

    val b = for (i <- 1 to 10) {
      i
    }
    println("b =" + b)

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

    val c = for (i <- 1 to 10) yield i
    println("c =" + c)

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

    val ints = for (i <- 1 to 10) yield i
    val d = ints
    println("d =" + d)

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

    val e: IndexedSeq[Int] = for (i <- 1 to 10) yield i
    println("e =" + e)
  }
}
Output result:
a =()
===============
b =()
===============
c =Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
===============
d =Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
===============
e =Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

While and do... While loop control

While and do... While are used in the same way as in the Java language.

While loop control

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

explain:

  • 1. A loop condition is an expression that returns a Boolean value

  • 2. A while loop is a statement that is judged first and then executed

  • 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 variables when using this statement to calculate the return result. If the variables need to be declared outside the while loop, it is equivalent to the internal of the loop, which has an impact on the external variables. Therefore, it is not recommended to use, but to use the for loop.

  • case

package day04

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
    }

    var b: Int = 0
    do {
      println("This is a do-while loop: " + b)
      b -= 1
    } while (b > 0)
  }
}
Output result:
This is a while loop: 10
 This is a while loop: 9
 This is a while loop: 8
 This is a while loop: 7
 This is a while loop: 6
 This is a while loop: 5
 This is a while loop: 4
 This is a while loop: 3
 This is a while loop: 2
 This is a while loop: 1
 This is a do-while loop: 0

Cycle interrupt

  • Basic description

   Scala's built-in control structure specifically removes break and continue in order to better adapt to functional programming. It is recommended to use functional style to solve the functions of break and continue instead of a keyword. Scala uses breakable control structure to realize break and continue functions.

  • case

Requirements:
1. Exit the loop by throwing an exception
2. Use the break method of the Breaks class in Scala to throw and catch exceptions

package day04

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
    }

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

    // 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)
      }
    )
    println("This is code outside the loop")
  }
}
Operation results:
0
1
2
=================
0
1
2
 This is code outside the loop

Original code breakable

def breakable(op: => Unit) {
    try {
      op
    } catch {
      case ex: BreakControl =>
        if (ex ne breakException) throw ex
    }
  }

optimization

Guide Package
import scala.util.control.Breaks._

package day04

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

object Test06_Break {
  def main(args: Array[String]): Unit = {
    // 2. Use the break method of the Breaks class in Scala to throw and catch exceptions
    breakable(
      for (i <- 0 until 5) {
        if (i == 3)
          break()
        println(i)
      }
    )
    println("This is code outside the loop")
  }
}
Operation results:
0
1
2
 This is code outside the loop

In the end! Please comment on the articles you like! ( • ̀ ω •́ ) ✧

Topics: Java Scala