1. if else
1.1 single branch
Syntax structure:
if (expr) { expr by true Statement executed when }
1.2 double branch
Syntax structure:
if (expr) { expr by true Statement executed when } else { expr by false Statement executed when }
1.3 multi branch
Syntax structure:
if (expr1) { expr1 by true Statement executed when } else if (expr2) { expr2 by true Statement executed when } ... else { All conditions are false Statement executed when }
1.4 nested branches
Syntax structure:
if (expr1) { if (expr2) { expr2 by true Statement executed when } else { expr2 by false Statement executed when } }
1.5 cases
Case: take out the maximum value of two numbers
val a = 2 val b = 3 var max = if (a>b) a else b
The output of the last line of the code block in Scala is the return value of the code block. When there is only one line of statements, it can be written on one line and {} is omitted
The ternary operation using Java can be written as max = (a > b)? a : b
⚠️ Note: in if else, if the return values of if and else branches are different, you need to use two types of public parent classes as the return value type. If you don't know, you can use Any type.
if (a>b) : Any ={ "abc" } else { a }
⚠️ Note: if there is no else branch and the else branch returns the return value Unit of {} by default, the return value type of this if else can be Any type.
if (a>b) : Any ={ "abc" }
2. while,do while
While, do while expressions fixedly return Unit
2.1 while
Syntax structure:
while (expr) { expr by true Statement executed repeatedly when }
Case: print Fibonacci series within 50
var first = 0 var second = 1 var fibonacci = 0 while (fibonacci < 50) { println(fibonacci) first = second second = fibonacci fibonacci = first + second }
2.2 do while
Syntax structure:
do { expr by true Statement executed repeatedly when } while (expr)
Case: calculate the sum of bits of a positive integer
var i = 53672 var sum = 0 do { sum += i % 10 i /= 10 } while (i > 0) println(sum) // 23
2.3 cycle interruption
Scala does not provide break and continue keywords to better adapt to functional programming.
Scala can use control loop conditions, function encapsulation + return or BreaksAPI!
Case: judge whether an integer contains even digits
// Use external Boolean to control loop conditions var i = 67253 var nonEven = true while (nonEven) { if (i % 10 % 2 == 0) { println("Contains even bits") nonEven = false } i /= 10 } // Use function encapsulation and return keyword var i = 67253 def checkEven(n: Int) { var tmp = n while (true) { if (tmp % 10 % 2 == 0) { println("Contains even bits") return } tmp /= 10 } } checkEven(i) // Using the BreaksAPI Breaks.breakable { while (true) { if (i % 10 % 2 == 0) { println("Contains even bits") Breaks.break() } i /= 10 } }
3. for loop
For in scala is called for derivation. Scala provides a powerful sequence derivation.
Syntax structure:
for (enumerators) { Circulatory body }
Enumerators: refers to a group of enumerators separated by semicolons. Enumerators can be composed of a generator that generates new variables and a guard
Generator: refers to an expression in the form of variable name < - set. The generator will remove an element from the set on the right of < - and assign it to the variable on the left of < - at each iteration
⚠️ Note: when there are multiple expressions in a row of the for derivation, you need to use; To block logic. Use () when the for derivation contains only one expression and {} when it contains multiple lines of expression
3.1 to,until
To is used to control the range of the cycle, closed left and closed right.
Usage of to: print numbers from 1 to 6
for (i <- 1 to 6){ print(i) }
until is also used to control the range of the cycle, closed on the left and open on the right.
Usage of unti: print numbers from 1 to 6
for (i <- 1 until 7){ print(i) }
3.2 guard
Guard: refers to an expression in the form of if expr. When expr is true, the loop body is executed. When expr is false, it is like the continue operation in Java. Skip this time and enter the next loop.
Usage of guard: print even numbers within 10
for (i <- 1 to 10 if i%2==0) println(i)
Only when the conditions in the guard are established can it enter the circulation body
3.3 step size (by)
Usage of by: print odd numbers within 10
for (i <- 1 to 10 by 2) println(i)
3.4 nested loops
Bubble sorting uses two-layer for loops, and multi-layer for loops are nested loops. Each cycle of the previous layer shall be executed in sequence, and all cycles of the next layer shall be executed once.
Usage of nested loops:
for (i <- 1 to 6; j <- 1 to 6){...}
Equivalent to:
for (i <- 1 to 6){ for (i <- 1 to 6){ ... } }
3.5 introduction of variables
Usage of introduced variables:
for (i <- 1 to 6; j = 6 - i){...}
Equivalent to:
for (i <- 1 to 6){ var j = 6 -i ... }
3.6 get return value (yield)
The elements that meet the guard conditions in the generator are brought into the loop body of for for for operation. Finally, all operation results can be collected into the (Vector) collection and returned by yield
yield usage: get the ASCII values of all characters in the string
val str = "abc" val ints = for (c <- str) yield c.asInstanceOf[Int] println(ints) // Output: Vector(97, 98, 99)
4. Multiple cycle judgment cases
Case: print 99 multiplication formula table!
// Leftward arrangement object CF_99 { def main(args: Array[String]): Unit = { for (i <- 1 to 9; j <- 1 to i) { print(s"${j}*${i}=${i * j}\t") if (i == j) println() } } }
// Rightward arrangement object CF_99 { def main(args: Array[String]): Unit = { for (i <- 1 to 9) { if (i < 9) print("\t\t" * (9 - i)) for (j <- 1 to i) { print(s"${j}*${i}=${i * j}\t") if (i == j) println() } } } }