Chapter 4 procedure flow control

1, If else... Sentence

Example code:

package com.lj.scala.main

import scala.io.StdIn

/**
  * @author Administrator
  * @create 2020-03-07 17:21
  */
object IfTest {

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

        var i = 0
        while (i < 7) {
            print("please enter name:")
            var name = StdIn.readLine()
            print("please enter age:")
            var age = StdIn.readInt()
            if (age > 0 && age < 18) {
                println(name + "age" + age + "year old, minor! ""
            } else if (age >= 18 && age <= 25) {
                Printf (""% s age% s age, youth! "! \n", name, age)
            } else if (age > 25 && age < 35) {
                println(s"$name" + "age" + s"$age" + "age, youth! ""
            } else {
                //Nested branch
                if (age > 35 && age < 60) {
                    println(s"$name" + s "age" + ", middle-aged and old! ""
                } else if (age >= 60 && age <= 80) {
                    println(s"$name" + s "age" + ", old age! ""
                } else (
                    Printf (% s age% s, lucky old man! \n", name, age)
                )
            }
            i += 1
        }

    }
}
========================Operation results====================================
Please enter your name: Jack
 Please enter age: 13
 Jack is 13 years old, under age!
Please enter your name: Tom
 Please enter age: 22
 Tom is 22 years old, young man!
Please enter name: Leo
 Please enter age: 31
 Leo is 31 years old, young!
Please enter your name: Rose
 Please enter age: 51
 Rose, age 51, middle-aged!
Please enter your name: Mary
 Please enter age: 60
 Marry is 60, old!
Please enter your name: Mali
 Please enter age: 85
 Mali age 85, lucky old man!
Please enter name: Amy
 Please enter age: 99
 Amy age 99, lucky old man!
========================Operation results====================================

2, switch branch statement

There is no switch statement in Scala, but it is handled by using match case.

3, for loop

Example code:

package com.lj.scala.main

/**
  * @author Administrator
  * @create 2020-03-07 21:06
  */
object ForTest {

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

        /**
          * Range data cycle mode
          * 1,start to end: Before and after closed interval
          * 2,start until end: Front closed rear open
          */
        var sum = 0
        for (i <- 1 to 3) {
            sum += i
        }
        println(s"to mode sum Summation:$sum")
        sum = 0
        for (i <- 1 until 3) {
            sum += i
        }
        printf("until mode sum Summation:%s\n", sum)
        sum = 0

        /**
          * Circular guard: that is, circular protection type (also known as conditional judgment is), if the protection type is true, it will enter the circular body, if it is false, it will skip, which is equivalent to continue
          *
          */

        for (i <- 0 to 100 if i%2 == 0) {
            sum += i
        }
        printf("Circular guard mode sum Summation:%s\n", sum)
        sum = 0
        // The above guard mode is equivalent to the following if judgment
        for (i <- 0 to 100) {
            if (i % 2 == 0) {
                sum += i
            }
        }
        printf("Circulation guard circulation body judgment method sum Summation:%s\n", sum)
        sum = 0

        /**
          * Introducing variables
          */

        for (i <- 1 to 3; j = 4 - i) {
            print("j=" + j + " ")
        }
        println("\n The second way is as follows")
        // The above variable is equivalent to the following code
        for (i <- 1 to 3) {
            var j = 4 - i
            print("j=" + j + " ")
        }
        println()

        /**
          * Nested loop
          */

        for (i <- 1 to 2; j <- 2 to 3) {
            printf("i = %s, j = %s\n", i, j)
        }
        println()

        /**
          * Loop return value
          * The keyword yield description in the code: returns the result processed during traversal to a Vector collection
          * yield i Put the i from each loop into the vector collection and return it to res
          * i Here is a code block. The following code illustrates this feature very well, so we can handle i
          */

        val res = for (i <- 0 to 10 if i%2 == 0) yield i
        println("Loop return value res:" + res)
        val res2 = for (i <- 0 to 10) yield {
            if (i%2 == 0) {
                i
            } else {
                i + "Not even numbers"
            }
        }
        println("Loop return value res2:" + res2)

        /**
          * Use curly braces {} instead of parentheses ()
          */
        for (i <- 1 to 3; j = i * 2) {
            println("i = " + i + "At that time, j = " + j)
        }
        // Replace () above with {}
        for {
            i <- 1 to 3
            j = i * 2
        } {
            println("{i} = {" + i + "}At that time,{j} = {" + j + "}")
        }

        /**
          * for Cycle control step uses Range(start, end, step)
          */

        for (i <- Range(153, 190, 20)) {
            println("Step data:" + i)
        }
        
    }
    
}
========================Operation result====================================
to mode sum Summation:6
until mode sum Summation:3
//sum of circular guard mode:2550
//sum up the judgment method of circulation guard circulation body:2550
j=3 j=2 j=1 
//The second way is as follows
j=3 j=2 j=1 
i = 1, j = 2
i = 1, j = 3
i = 2, j = 2
i = 2, j = 3

//Loop return value res:Vector(0, 2, 4, 6, 8, 10)
//Loop return value res2:Vector(0, 1Not even numbers, 2, 3Not even numbers, 4, 5Not even numbers, 6, 7Not even numbers, 8, 9Not even numbers, 10)
i = 1At that time, j = 2
i = 2At that time, j = 4
i = 3At that time, j = 6
{i} = {1}At that time,{j} = {2}
{i} = {2}At that time,{j} = {4}
{i} = {3}At that time,{j} = {6}
//Step data:153
//Step data:173
========================Operation result====================================

4, while loop control

Example code:

package com.lj.scala.main

/**
  * @author Administrator
  * @create 2020-03-07 21:56
  */
object WhileTest {

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

        /**
          * while Cyclic syntax format
          * while () {
          *     Loop body statement
          *     Cyclic variable iteration
          * }
          */
        
        var flag = true
        var i = 2
        while (flag) {
            println("Operation result:" + (i * 3))
            i += 1
            if (i == 5) {
                flag = false
            }
        }

    }

}
========================Operation result====================================
//Operation result:6
//Operation result:9
//Operation result:12
========================Operation result====================================

Five, do... while loop statement

Example code:

package com.lj.scala.main

/**
  * @author Administrator
  * @create 2020-03-07 22:03
  */
object DoWhileTest {

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

        /**
          * do...while Cyclic syntax format
          *
          * Loop variable initialization
          * do {
          *     Loop body statement
          *     Cyclic variable iteration
          * } while(Cycle conditions)
          *
          */

        var i = 0
        do{
            println("Operation result:" + (i * 17))
            i += 26
        } while ( i < 98)

    }

}
========================Operation result====================================
//Operation result:0
//Operation result:442
//Operation result:884
//Operation result:1326
========================Operation result====================================

6, End of while cycle

Basic explanation

	Scala's built-in control structure specifically removes break and continue, which is to better adapt to functional programming. Functions are recommended
 Style solves the function of break and contain, not a keyword.

Example code:

package com.lj.scala.main

import util.control.Breaks._

/**
  * @author Administrator
  * @create 2020-03-07 22:13
  */
object WhleBreakTest {

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

        /**
          * breakable()function
          * breakable is a higher-order function: the function that can receive the function is a higher-order function
          */

        /*def breakable(op: => Unit){
            try {
                op
            } catch {
                case ex: BreakControl =>
                    if (ex ne breakException) throw ex
            }
        }
        op: => Unit Indicates that the received parameter is a function without input and return value
        That is, you can simply understand that you can receive a code block
        */

        // breakable handles the exception thrown by break(), and the code continues to execute
        var n = 1
        breakable{
            while ( n <= 20) {
                n += 5
                println("n = " + n)
                if (n > 18) {
                    // Final cut while
                    break()
                }
            }
        }
        println("end!!!")

    }

}
========================Operation result====================================
n = 6
n = 11
n = 16
n = 21
//end!!!
========================Operation result====================================

How to achieve the effect of continue

	Scala's built-in control structure specifically removes continue to better adapt to functional programming. You can use if - else or
 Loop guard to achieve the effect of continue

Learning from: Mr. Han Shunping, shangxuetang, Beijing -- Scala of big data technology in shangsilicon Valley
Improve a little every day, maybe one day you will become so small!!!

Published 20 original articles, won praise 6, visited 20000+
Private letter follow

Tags: Scala Programming Big Data

Posted on Sun, 08 Mar 2020 21:59:19 -0700 by ldoozer