1. Branch control if else
Let the program execute selectively. There are three kinds of branch control: single branch, double branch and multi branch
1.1 single branch
1) Basic grammar
if (Conditional expression) { Execute code block }
Description: when the conditional expression is true, the code of {} will be executed.
2) Case
// Enter a number. If it is even, output even val number = StdIn.readInt() if(number % 2 == 0) { println("even") }
1.2 double branch
1) Basic grammar
if (Conditional expression) { Execute code block 1 } else { Execute code block 2 }
2) Case
// Enter a number. If it is an odd number, output odd; if it is an even number, output even val number = StdIn.readInt() if(number % 2 == 0) { println("even") } else { println("odd") }
1.3 multi branch
1) Basic grammar
if (Conditional expression 1) { Execute code block 1 } else if (Conditional expression 2) { Execute code block 2 } ...... else { Execute code block n }
2) Case
// Enter a number less than 100. If it is an odd number, it will output odd; if it is an even number, it will output even; if it is greater than 100, it will output out of range val number = StdIn.readInt() if(number > 100) { println("Out of range") } else if(number % 2 == 0) { println("even") } else { println("odd") }
be careful:
- The if else expression in Scala actually has a return value. The specific return value depends on the last line of the code body that meets the conditions.
val number = StdIn.readInt() val res: String = if(number > 100) { "Out of range" } else if(number % 2 == 0) { "even" } else { "odd" }
- The return value types in Scala are inconsistent. Take their common ancestor type.
val number = StdIn.readInt() val res: Any = if(number > 100) { number } else if(number % 2 == 0) { "even" } else { "odd" }
- Ternary operators in Java can be implemented with if else
If there is only one line of logical code in braces {}, braces can be omitted. If braces are omitted, if works only on the nearest line of logical code.
val number = StdIn.readInt() val res: String = if(number % 2 == 0) "even" else "odd"
1.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.
1) Basic grammar
if(){ if() { } else{ } }
2) Case
// Enter a number less than 100. If it is an odd number, it will output odd; if it is an even number, it will output even; if it is greater than 100, it will output out of range val number = StdIn.readInt() val res: String = if(number > 100) { "Out of range" } else { if(number % 2 == 0) { "even" } else { "odd" } }
2. 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 for derivation or for expression.
2.1 range data cycle (To)
1) Basic grammar
for(i <- 1 to 3) { print(i + " ") // 1 2 3 }
(1) i represents the variable of the loop, < - specify to
(2) i will cycle from 1-3 and close back and forth
2) Case
// Output test1-test5 for(i <- 1 to 5) { println("test" + i) }
2.2 range data cycle (Until)
1) Basic grammar
for(i <- 1 until 3) { print(i + " ") // 1 2 }
(1) The difference between this method and the previous one is that i is from 1 to 3-1
(2) That is, the range of front closing and rear opening
2) Case
// Output test1-test5 for(i <- 1 until 5 + 1) { println("test" + i) }
2.3 cycle guard
1) Basic grammar
for(i <- 1 to 3 if i != 2) { print(i + " ") // 1 3 }
(1) Circular guard, i.e. circular protection type (also known as conditional judgment type, guard). If the protected type is true, it will enter the loop body, and if it is false, it will skip, similar to continue.
(2) The following code is equivalent to the previous code
for (i <- 1 to 3){ if (i != 2) { print(i + " ") } }
2) Case
// Output test0-test5 for(i <- -1 to 5 if i != -1) { println("test" + i) }
2.4 cycle step
1) Basic grammar
for (i <- 1 to 10 by 2) { print(i + " ") // 1 3 5 7 9 }
Note: by indicates the step size
2) Case
// Output all even numbers from 1 to 10 for (i <- 0 to 10 by 2) { println(i + " ") // 0 2 4 6 8 10 }
2.5 nested loops
1) Basic grammar
for(i <- 1 to 3; j <- 1 to 3) { println(" i =" + i + " j = " + j) } /* 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 */
Note: there is no keyword, so it must be added after the range; To block logic
2) Case
// The code here is equivalent to the previous code for (i <- 1 to 3) { for (j <- 1 to 3) { println("i = " + i + " j= " + j) } }
2.6 introduction of variables
1) Basic grammar
for(i <- 1 to 3; j = 4 - i) { println("i = " + i + " j = " + j) } /* i= 1 j= 3 i= 2 j= 2 i= 3 j= 1 */
explain:
(1) When there are multiple expressions in a row of the for derivation, it should be added; To block logic
(2) 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 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) // Same as the previous code output }
2) Case
// The code here is the same as the previous code for (i <- 1 to 3) { var j = 4 - i println("i =" + i + " j =" + j) }
2.7 cycle return value
1) Basic grammar
val res = for(i <- 1 to 10) yield i println(res) // Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Description: return the results processed during traversal to a new Vector collection, and use the yield keyword.
Note: it is rarely used in development.
2) Case
// Multiply all the values in the original data by 2 and return the data to a new set. var res = for(i <-1 to 10) yield { i * 2 } println(res) // Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
2.8 reverse order printing
1) Note: if you want to print a group of data in reverse order, you can use reverse.
2) Case
// Print 10 to 1 in reverse order for(i <- 1 to 10 reverse){ println(i) }
3.While and do... While loop control
While and do... While are used in the same way as in the Java language.
3.1 While cycle control
1) 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 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 variables when using this statement to calculate and return results, and variables need to be declared outside the while loop, which is equivalent to the internal of the loop and affects the external variables. Therefore, it is not recommended to use, but to use the for loop. (in the environment of big data, parallel processing is inevitable. If a while loop is used, the internal of the loop will affect external variables, which is easy to cause problems in parallel processing)
2) Case
// Output test1-test5 var i = 1 while(i < 6) { println('test' + i) i += 1 }
3.2 do... while cycle control
1) Basic grammar
Loop variable initialization; do { Circulatory body(sentence) Cyclic variable iteration } while(Cycle condition)
explain:
(1) A loop condition is an expression that returns a Boolean value
(2) do... while loop is executed first and then judged
2) Case
// Output test1-test5 var i = 1 do { println('test' + i) i += 1 } while(i < 6)
4. Cycle interruption
1) 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, rather than a keyword. The breakable control structure is used in scala to implement break and continue functions.
2) Case
// Exit the loop in an abnormal way try { for (elem <- 1 to 10) { if (elem == 5) throw new RuntimeException println(elem) } } catch { case e: Exception => // Do nothing, just exit the loop } println("Extracorporeal circulation")
// Use Scala's own functions to exit the loop import scala.util.control.Breaks Breaks.breakable( for (elem <- 1 to 10) { println(elem) if (elem == 5) Breaks.break() } )
// Omit break import scala.util.control.Breaks._ breakable { for (elem <- 1 to 10) { if (elem == 5) break println(elem) } }
5. Multiple cycles
1) Basic description
(1) A nested loop is formed when one loop is placed in another loop. Among them, for, while, do... While can be used as outer loop and inner loop. [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.
2) Case
// Print 99 multiplication table for (i <- 1 to 9) { for (j <- 1 to i) { print(j + "*" + i + "=" + (i * j) + "\t") } println() }