scala -- process control + yield derivation + scala does not have continue or break?

1. Process control structure

1.1 general

In the actual development, we have to write thousands of lines of code. The order of the code is different, and the execution results will certainly be affected. Some codes can be executed only if they meet specific conditions, and some codes need to be executed repeatedly. How to reasonably plan these codes? This requires: process control structure

1.2 classification

  • Sequential structure

  • Select (Branch) structure

  • Cyclic structure

    Note: the process control structures in Scala and Java are basically the same

2. Sequential structure

2.1 general

Sequential structure means that the program is executed line by line from top to bottom and from left to right without any judgment and jump

As shown in the figure:

Note: sequential structure is the default process control structure of Scala code

2.2 code demonstration

val a = 10
println("a: " + a)	//The print result is 10

println("The keyboard is broken, ")
println("Monthly salary over 10000! ")

2.3 thinking questions

What should the print result of the following line of code be?

println(10 + 10 + "Hello,Scala" + 10 + 10)

Tip: the code is executed line by line from top to bottom and from left to right

3. Select structure (if statement)

3.1 general

Selection structure means that the execution of some codes depends on specific judgment conditions. If the judgment conditions are true, the code will be executed; otherwise, the code will not be executed

3.2 classification

  • Single branch
  • Double branch
  • Multi branch

3.3 single branch

The so-called single branch refers to an if statement with only one judgment condition

3.3.1 format
if(Relational expression) {
    //Specific code
}

Note: whether the relational expression is simple or complex, the result must be a Boolean value

3.3.2 execution process
  1. First execute the relational expression to see whether the result is true or false

  2. If true, the specific code will be executed; otherwise, it will not be executed

  3. As shown in the figure:

3.3.3 example

**Requirements:**

Define a variable to record a student's score. If the score is greater than or equal to 60, print: pass score

Reference code

//Define variables and record grades
val score = 61
//Judge whether the score is not less than 60 points
if(score >= 60) {
    println("Pass the grade")
}

3.4 double branch

The so-called double branch refers to an if statement with only two judgment conditions

3.4.1 format
if(Relational expression) {
    //Code 1
} else {
    //Code 2
}
3.4.2 execution process
  1. First execute the relational expression to see whether the result is true or false
  2. If true, execute code 1. If false, execute code 2
  3. As shown in the figure:

3.4.3 example

**Requirements:**

Define a variable to record a student's score. If the score is greater than or equal to 60, print: the score is passed, otherwise the score is failed

Reference code

//Define variables and record grades
val score = 61
//Judge whether the score is not less than 60 points
if(score >= 60) {
    println("Pass the grade")
} else {
    println("Fail in grade")
}

3.5 multi branch

The so-called multi branch refers to if statements with multiple judgment conditions

3.5.1 format
if(Relationship expression 1) {
    //Code 1
} else if(Relational expression 2) {
    //Code 2
}else if(Relational expression n) {	//else if can have multiple groups
    //Code n
} else {
    //Code n+1 			  // When all relational expressions fail, execute the code here
}
3.5.2 execution process
  1. First execute relational expression 1 to see whether the result is true or false
  2. If true, execute code 1 and end the branch statement. If false, execute relationship expression 2 to see whether the result is true or false
  3. If true, execute code 2. End of branch statement. If false, execute relational expression 3 to see whether the result is true or false
  4. And so on, until all relational expressions are not satisfied, execute the code in the last else
  5. As shown in the figure:
3.5.3 example

**Requirements:**

Define a variable to record a student's performance and issue corresponding rewards according to the performance. The reward mechanism is as follows:

[90, 100] - > one set of VR equipment

[80, 90) - > one set of examination papers

[0, 80) - > one set of combination boxing

Other - > invalid score

Reference code

//Define variables and record grades
val score = 80
//Corresponding rewards will be given according to the results
if(score >= 90 && score <= 100) {
    println("VR One set of equipment")
} else if(score >= 80 && score < 90) {
    println("A set of examination papers")
} else if(score >= 0 && score < 80) {
    println("Combination boxing")
} else {
    println("Invalid score")
}

3.6 precautions

When using the if statement, you should pay attention to the following three points:

  1. Like Java, in Scala, if the logical code in braces {} has only one line, the braces can be omitted
  2. In scala, conditional expressions also have return values
  3. In scala, there is no ternary expression, so you can use if expression instead of ternary expression

Example

Define a variable sex and then a result variable. If sex is equal to "male", result is equal to 1, otherwise result is equal to 0

Reference code

//Define variables that represent gender
val sex = "male"
//Define variables and record the return value and results of if statements
val result = if(sex == "male") 1 else 0
//The print result is result: 1
println("result: " + result)

3.7 nested branches

Sometimes, we will involve "combinatorial judgment", that is, one branch structure is nested in another branch structure, which is called nested branch. The branch structure inside is called inner branch, and the branch structure outside is called outer branch

Example

Define three variables a, B and C with initialization values of 10, 20 and 30 respectively. Obtain the maximum value through the if branch statement

Train of thought analysis

  1. Define three variables a, B and C, and record the values to be operated respectively
  2. Define the variable max to record the maximum value obtained
  3. First judge whether a is greater than or equal to b
  4. If the condition holds, a is large (or equal to b), then compare the values of a and c to obtain the maximum value, and assign the result to the variable max
  5. If the condition does not hold, it means that b is large. Then compare the values of b and c to obtain the maximum value, and assign the result to the variable max
  6. At this time, max records the maximum values of three variables a, B and C, which can be printed

Reference code

//1. Define three variables a, B and C, and record the values to be operated respectively
val a = 10
val b = 20
val c = 30
//2. Define the variable max to record the maximum value obtained
var max = 0
//3. First judge whether a is greater than or equal to b
if(a >= b) {
    //4. Go here to explain that a is large (or equal to b), and then compare the values of a and c
    max = if(a >= c) a else c
} else {
    //5. Go here to show that b is large, and then compare the values of b and c
    max = if(b >= c) b else c
}
//6. Print the value of max
println("max: " + max)

Note: nesting generally does not exceed 3 layers

3.8: extension block expression

  • In scala, {} is used to represent a block expression
  • Like if expressions, block expressions have values
  • Value is the value of the last expression

problem

What is the value of variable a in the following code?

val a = {
   println("1 + 1")
   1 + 1
}
println("a: " + a)

4. Circulation structure

4.1 General

Loop refers to the change of things over and over again. The loop structure in scala refers to a code structure that enables a part of code to be executed repeatedly according to the number of times or certain conditions. For example, if you print "Hello, Scala!" 10 times, you need to write the output statement 10 times, but if you implement it through loop, the output statement only needs to be written once, which becomes very simple

4.2 classification

  • for loop
  • while Loop
  • do.while loop

Note: the for loop is recommended for these three loops because its syntax is more concise and elegant

4.3 for loop

In Scala, the format and usage of for are different from those in Java. The for expression in scala is more powerful

4.3.1 format
for(i <- expression/array/aggregate) {
    //Logic code
}

Note: the execution process is consistent with Java

4.3.2 simple cycle

**Requirements:**

Print 10 times "Hello, Scala!"

**Reference code:**

//Define a variable and record numbers from 1 to 10
val nums = 1 to 10	//to is a keyword in Scala
//Print the specified content through the for loop
for(i <- nums) {
     println("Hello, Scala! " + i)
}

**The above code can be abbreviated as:**

for(i <- 1 to 10) println("Hello, Scala! " + i)
4.3.3 nested loops

**Requirements: * * use the for expression to print the following characters, and only one "*" can be output at a time

*****
*****
*****

step

  1. Use the for expression to print 3 rows and 5 columns of stars
  2. Wrap every 5 stars printed

Reference code

//Writing method 1: common writing method
for(i <- 1 to 3) {		//Number of outer loop control lines
    for(j <- 1 to 5) {	//Number of internal loop control columns
        print("*")		//Print one at a time*
    }
    println()			//After printing a line (5 *), remember to wrap the line
}

//Writing method 2: compressed version
for(i <- 1 to 3) {		
    //This is two lines of code
    for(j <- 1 to 5) if(j == 5) println("*") else print("*")
}

//Writing method 3: combined version
for(i <- 1 to 3; j <- 1 to 5) if(j == 5) println("*") else print("*")
4.3.4 guard

In the for expression, you can add an if judgment statement, which is called guard. We can use guard to make the for expression more concise.

grammar

for(i <- expression/array/aggregate if expression) {
    //Logic code
}

Example

Use the for expression to print numbers between 1 and 10 that can be divided by 3

Reference code

// Add guards and print numbers that can divide by 3
for(i <- 1 to 10 if i % 3 == 0) println(i)
4.4.5 for derivation

The for loop in Scala also has a return value. In the body of the for loop, you can use the yield expression to build a set (which can be simply understood as a set of data). We call the for expression using yield as a derivation

Example

Generate a set of 10, 20, 30... 100

Reference code

// For derivation: the for expression starts with yield, which will build a collection
val v = for(i <- 1 to 10) yield i * 10
println(v)

4.4 while loop

The while loop in scala is consistent with that in Java, so it's very easy to learn

4.4.1 format
Initialization condition
while(Judgment conditions) {
    //Circulatory body
    //Control conditions
}
4.4.2 execution process
  1. Execute initialization conditions
  2. Execute the judgment condition to see whether the result is true or false
  3. If false, the loop ends
  4. If true, the loop body is executed
  5. Execute control conditions
  6. Return to step 2 and repeat
4.4.3 example

**Requirements:**

Print numbers 1-10

Reference code

//Initialization condition
var i = 1
//Judgment conditions
while(i <= 10) {
    //Circulatory body
    println(i)
    //Control conditions
    i = i + 1
}

4.5 do.while loop

The do.while loop in scala is consistent with that in Java, so it's very easy to learn

4.4.1 format
Initialization condition
do{
    //Circulatory body
    //Control conditions
}while(Judgment conditions) 
4.4.2 execution process
  1. Execute initialization conditions
  2. Execute the loop body
  3. Execute control conditions
  4. Execute the judgment condition to see whether the result is true or false
  5. If false, the loop ends
  6. If true, return to step 2 to continue

be careful:

  1. do.while Loop whether the judgment condition is true or not, The loop body is executed once.
  2. for loop, while If the judgment condition is not tenable, The loop body is not executed.
4.4.3 example

**Requirements:**

Print numbers 1-10

Reference code

//Initialization condition
var i = 1
do{
    //Circulatory body
    println(i)
    //Control conditions
    i = i + 1
}while(i <= 10)	//Judgment conditions

4.6 break and continue

  • In scala, break/continue keywords like Java and C + + have been removed
  • If you must use break/continue, you need to use the break and break methods of the Breaks class under the scala.util.control package.
4.6.1 implementation of break

usage

  1. Guide bag

    import scala.util.control.Breaks._

  2. Wrap for expressions with breakable

  3. Where the for expression needs to exit the loop, add a break() method call

Example

Use the for expression to print numbers from 1 to 10. If the number 5 is encountered, exit the for expression

Reference code

// Import Break under scala.util.control package
import scala.util.control.Breaks._

breakable{
    for(i <- 1 to 10) {
        if(i == 5) break() else println(i)
    }
}
4.6.2 implementation of continue

usage

The implementation of continue is similar to break, but with one difference:

be careful:

  1. The implementation of break is to wrap the whole for expression with breakable {}
  2. The implementation of continue is to use breakable {} to include the loop body of the for expression

Example

Use the for expression to print all numbers between 1 and 10 that cannot be divided by 3

// Import Break under scala.util.control package    
import scala.util.control.Breaks._

for(i <- 1 to 100 ) {
    breakable{
        if(i % 3 == 0) break()
        else println(i)
    }
}

5. Comprehensive cases

5.1 99 multiplication table

**Requirements:**

Print the 99 multiplication table as shown below:

step

  1. The number of lines printed is controlled by an outer loop

  2. The number of columns printed per row is controlled by inner loop

    Note: because the number of columns increases with the number of rows, that is:

    Number of rowsTotal number of columns in this row
    11
    22
    33
    nn

    Conclusion: if i is used to represent the number of rows, the value range of the number of columns in this row is: [1, i]

Reference code

  • Method 1: common writing
//External circulation control line
for(i <- 1 to 9) {		
    //Inner loop control column
    for(j <- 1 to i) {
        print(s"${i} * ${j} = ${i * j}\t")
    }
    println()			//Don't forget to wrap
}
  • Method 2: combined version
//External circulation control line
for(i <- 1 to 9; j <- 1 to i) {		
    print(s"${i} * ${j} = ${i * j}\t")
    if(j == i) println()	//Don't forget to wrap
}

Keywords: Java Scala Database Big Data Data Warehouse

Added by xmanofsteel69 on Fri, 26 Nov 2021 02:52:49 +0200