当前位置:网站首页>7. Scala process control

7. Scala process control

2022-07-05 00:33:00 liangzai2048

Process control

Branch control if-else

   Let the program execute selectively , There are three branches : Single branch 、 Double branch 、 Multiple branches

Single branch

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

explain : When the conditional expression is true when , Will execute () Code for .

  • Case study

demand : Enter the age of the person , If the comrade is younger than 18 year , The output “ A minor ”

Double branch

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

explain : When the conditional expression is true when , Will execute () Code for
When the conditional expression is false when , Will execute else Code for

  • Case study

demand : Enter the age of the person , If the comrade is younger than 18 year , The output “ A minor ”, Otherwise output “ adult ”

Multiple branches

  • 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 
}

explain : When the conditional expression is true when , Will execute () Code for
When the conditional expression is false when , Will execute else Code for

  • Case study

demand :
When the age is less than or equal to 6 Time output “ childhood ”
When the age is less than 18 Time output “ A minor ”
When the age is less than 35 Time output “ adult ”
When the age is less than 60 Time output “ middle-aged ”
Otherwise output “ The elderly ”

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(" A minor ")
    }

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

    // 3、 Multiple branches 
    if (age <= 6) {
    
      println(" childhood ")
    } else if (age < 18) {
    
      println(" A minor ")
    } else if (age < 35) {
    
      println(" adult ")
    } else if (age < 60) {
    
      println(" middle-aged ")
    } else {
    
      println(" The elderly ")
    }
  }
}
 Output results :
 Please enter your age :
24
 adult 
===============
 adult 
=============
 adult 

The return value of the 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()

    //  The return value of the branch statement 
    val result: String = if (age <= 6) {
    
      println(" childhood ")
      " childhood "
    } else if (age < 18) {
    
      println(" A minor ")
      " A minor "
    } else if (age < 35) {
    
      println(" adult ")
      " adult "
    } else if (age < 60) {
    
      println(" middle-aged ")
      " middle-aged "
    } else {
    
      println(" The elderly ")
      " The elderly "
    }
    println("result:" + result)
  }
}
 Output results :
 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()

    //  The return value of the branch statement 
    val result1: String = if (age <= 6) {
    
      println(" childhood ")
      " childhood "
    } else if (age < 18) {
    
      println(" A minor ")
      " A minor "
    } else if (age < 35) {
    
      println(" adult ")
      " adult "
    } else if (age < 60) {
    
      println(" middle-aged ")
      " middle-aged "
    } else {
    
      println(" The elderly ")
      " The elderly "
    }
    println("result1:" + result1)
  }
}
 Output results :
 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()

    //  The return value of the branch statement 
    val result2: Any = if (age <= 6) {
    
      println(" childhood ")
      " childhood "
    } else if (age < 18) {
    
      println(" A minor ")
      age
    } else if (age < 35) {
    
      println(" adult ")
      age
    } else if (age < 60) {
    
      println(" middle-aged ")
      age
    } else {
    
      println(" The elderly ")
      age
    }
    println("result2:" + result2)
  }
}
 Output results :
 Please enter your age 
25
 adult 
result2:25

Any You can return any type of return value

Scala There is no ternary operator

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 There is no ternary operator  String res2 = (age >=18)? " adult " : " A minor "
    val res: String = if (age >= 18) {
    
      " adult "
    } else {
    
      " A minor "
    }
    println("res" + res)

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

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

    // String res3 = (age >=18)? " adult " : " A minor "
  }
}
 Output results :
 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、 Nesting branches 
    if (age >= 18) {
    
      println(" adult ")
      if (age >= 35) {
    
        if (age >= 60) {
    
          println(" The elderly ")
        } else {
    
          println(" middle-aged ")
        }
      }
    } else {
    
      println(" A minor ")
      if (age <= 6) {
    
        println(" childhood ")
      }
    }
  }
}
 Output results :
 Please enter your age :
23
 adult 

For Cycle control

  Scala Also for the for Loop, a common control structure, provides many features , these for The nature of the cycle is called for Derivation or for expression .

Range data cycle (To)

  • Basic grammar
for (i < -1 to 3) {
	print(i + " ")
}
println()
  • i The variable representing the loop ,<- Regulations to

  • i Will be from 1-3 loop , Close back and forth

  • Case study

demand : Output 5 sentence " handsome young man , You are handsome !"

package day04

object Test02_ForLoop {
    
  def main(args: Array[String]): Unit = {
    
    // java for grammar :for(int i = 0;i < 5;i++){System.out.println(i + ".hello world");}

    //  Range traversal 
    for (i <- 1 to 5) {
    
      println(i + ". handsome young man , You are handsome !")
    }

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

    for (i <- 6.to(10)) {
    
      println(i + ". handsome young man , You are handsome !")
    }

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

    for (i <- Range(1, 10)) {
    
      println(i + ". handsome young man , You are handsome !")
    }

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

    for (i <- 1 until (10)) {
    
      println(i + ". handsome young man , You are handsome !")
    }
  }
}
 Output results :
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. handsome young man , You are handsome !
2. handsome young man , You are handsome !
3. handsome young man , You are handsome !
4. handsome young man , You are handsome !
5. handsome young man , You are handsome !
===============
6. handsome young man , You are handsome !
7. handsome young man , You are handsome !
8. handsome young man , You are handsome !
9. handsome young man , You are handsome !
10. handsome young man , You are handsome !
===============
1. handsome young man , You are handsome !
2. handsome young man , You are handsome !
3. handsome young man , You are handsome !
4. handsome young man , You are handsome !
5. handsome young man , You are handsome !
6. handsome young man , You are handsome !
7. handsome young man , You are handsome !
8. handsome young man , You are handsome !
9. handsome young man , You are handsome !
===============
1. handsome young man , You are handsome !
2. handsome young man , You are handsome !
3. handsome young man , You are handsome !
4. handsome young man , You are handsome !
5. handsome young man , You are handsome !
6. handsome young man , You are handsome !
7. handsome young man , You are handsome !
8. handsome young man , You are handsome !
9. handsome young man , You are handsome !

A collection of traverse

package day04

object Test02_ForLoop {
    
  def main(args: Array[String]): Unit = {
    
    // 2、 A collection of traverse 
    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)
    }
  }
}

 Running 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 + " ")
}
  • Cycle guard , Cycle protection mode ( Also known as conditional judgment , The guards ). The protection type is true Then go inside the circulatory body , by false Then skip , Be similar to continue(Scala There is no )

  • The above code is equivalent to

for (i <- 1 to 3) {
if (1 != 2) {
	println(i + " ")
}
}
  • Case study
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 results :
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 results :
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)
}

No keywords , So we must add ; To cut off logic

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

object Test02_ForLoop {
    
  def main(args: Array[String]): Unit = {
    
    // 5、 A nested loop 
    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 results :
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 the 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 results :
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)
}
  • for When there are more than one expression in a row of the derivation , So add ; To cut off logic
  • for The derivation has an unwritten Convention : When for Use parentheses when the derivation contains only a single expression , When multiple expressions are included , Usually one expression per line , And use curly braces instead of parentheses , as follows
for {
	i <- 1 to 3
	j = 4 - i
} {
	println("i =" + i + " j =" + j)
}
  • Case study
package day04

object Test02_ForLoop {
    
  def main(args: Array[String]): Unit = {
    
    // 5、 A nested loop 
    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 introduces variables 
    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 results :
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 results :
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)

explain : Return the results processed during traversal to a new Vector Collection , Use yield keyword .

Be careful : Rarely used in development

  • Case study

demand : 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 results :
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 Cycle control

While and do…While The use of and Java The usage is the same in language .

While Cycle control

  • Basic grammar
 Loop variable initialization 
while( The loop condition ) {
	 The loop body ( sentence )
	 Loop variable iteration 
}

explain :

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

  • 2、while A loop is to judge before executing a statement

  • 3、 And for The statements are different ,while Statement has no return value , The whole while The result of the statement is Unit type ()

  • 4、 because while There is no return value , So when you want to use this statement to calculate the return result , It's inevitable to use variables , Variables need to be declared in while The outside of the cycle , So it's equivalent to the inside of the loop having an impact on the outside variables , So... Is not recommended , It's recommended for loop .

  • Case study

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 results :
 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 break

  • Basic explanation

  Scala The built-in control structure specifically removes break and continue, In order to better adapt to functional programming , It is recommended to use the functional style to solve break and continue The function of , Not a keyword .Scala Use in breakable Control structure to achieve break and continue function .

  • Case study

demand :
1、 Throw an exception , Exit loop
2、 Use Scala Medium Breaks Class break Method , Throw and catch exceptions

package day04

import scala.util.control.Breaks

object Test06_Break {
    
  def main(args: Array[String]): Unit = {
    
    // 1、 Throw an exception , Exit loop 
    try {
    
      for (i <- 0 until 5) {
    
        if (i == 3)
          throw new RuntimeException
        println(i)
      }
    } catch {
    
      case e: Exception => //  Don't do anything? , Just exit the loop 
    }

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

    // 2、 Use Scala Medium Breaks Class break Method , Throw and catch exceptions 
    Breaks.breakable(
      for (i <- 0 until 5) {
    
        if (i == 3)
          Breaks.break()
        println(i)
      }
    )
    println(" This is the code outside the loop ")
  }
}
 Running results :
0
1
2
=================
0
1
2
 This is the code outside the loop 

breakable Original code

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

Optimize

Guide pack
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 Scala Medium Breaks Class break Method , Throw and catch exceptions 
    breakable(
      for (i <- 0 until 5) {
    
        if (i == 3)
          break()
        println(i)
      }
    )
    println(" This is the code outside the loop ")
  }
}
 Running results :
0
1
2
 This is the code outside the loop 

After all ! If you like liangzai's articles, please comment below !( •̀ ω •́ )*

原网站

版权声明
本文为[liangzai2048]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141119169579.html