4. Procedural Flow Control

01. Overview of process control Flow control statements are statements that control the order in which statements are ex...
2.1, Branch statement 1:if-else structure
2.2, Branch statement 2:switch-case structure
4.1, for cycle
4.2, while cycle
4.3, do-while cycle
4.4. Nested Loop Structure
Use of 4.5, break, continue

01. Overview of process control

Flow control statements are statements that control the order in which statements are executed in a program. They can be combined into small logic modules that can perform certain functions.

Its process control mode uses three basic process structures specified in structured program design, namely:

  • Sequential structure
  • Branch structure
  • Cyclic structure

1. Sequential structure

The program executes line by line from top to bottom without any judgment or jump.

2. Branch structure

  • Selectively execute a piece of code, depending on the condition.
  • There are two branch statements if...else and switch-case.

3. Cycle structure

  • Repeatedly executes a piece of code based on a loop condition.
  • There are three loop statements: while, do...while, for.
  • Note: JDK1.5 provides foreach loops to easily traverse collections and array elements.
02. Sequential structure

Use legal forward references when defining member variables in Java. For example:

03. Branch statement

2.1, Branch statement 1:if-else structure

1. if-else Instructions:

  • Conditional expressions must be Boolean expressions (relational or logical expressions), Boolean variables;
  • When a statement block has only one execution statement, a pair of {} can be omitted, but it is recommended to keep it.
  • if-else statement structure, which can be nested as needed;
  • When the if-else structure is "multiple choice", the final else is optional and can be omitted as needed.
  • When multiple conditions are mutually exclusive, the order between the conditional judgment statement and the execution statement does not matter. When multiple conditions are containment, the order between "small up and large down/parent up and down".

2. Exercises

/* if-else in branching structure 1. Three Structures First: if(Conditional Expression) { Execution Expression } Second: if(Conditional Expression) { Execute Expression 1 }else{ Execute Expression 2 } Third: if(Conditional Expression) { Execute Expression 1 }else if{ Execute Expression 2 }else if(Conditional Expression) { Execute Expression 3 } ... else{ Execute expression n } */ class IfTest{ public static void main(String[] args){ //Example 1 int heartBeats = 75; if(heartBeats < 60 || heartBeats > 100){ System.out.println("Further inspection is required"); } System.out.println("End of check"); //Example 2 int age = 23; if(age < 18){ System.out.println("You can also see animations"); }else{ System.out.println("You can watch tech movies"); } //Example 3 if(age < 0){ System.out.println("The data you entered is inappropriate"); }else if(age < 18){ System.out.println("You're still a teenager"); }else if(age < 35){ System.out.println("You're still a young man"); }else if(age < 60){ System.out.println("You're still middle-aged"); }else if(age < 120){ System.out.println("You're old."); }else{ System.out.println("You're an immortal"); } } }

2.1.1, Input statement

/* How to get different types of variables from the keyboard requires the Scanner class Specific steps: 1.Import: java.util.Scanner; 2.Scanner Instantiation; 3.Call the related method of the Scanner class to get the specified variable. */ import java.util.Scanner; class IFTest{ public static void main(String[] args){ //Declare a Scanner Scanner scan = new Scanner(System.in); int num = scan.nextInt(); System.out.println(num); } }
/* How to get different types of variables from the keyboard requires the Scanner class Specific steps: 1.Import: java.util.Scanner; 2.Scanner Instantiation; 3.Call the related method of the Scanner class to get the specified variable. */ import java.util.Scanner; class IFTest{ public static void main(String[] args){ //Scanner instantiation Scanner scan = new Scanner(System.in); System.out.println("Please enter your name:"); String name = scan.next(); System.out.println(name); System.out.println("Please enter your age:"); int age = scan.nextInt(); System.out.println(age); System.out.println("Please enter your weight:"); double weight = scan.nextDouble(); System.out.println(weight); System.out.println("Are you single?(true/false)"); boolean isLive = scan.nextBoolean(); System.out.println(isLive); //char type fetch, Scanner does not provide related methods, can only get a string System.out.println("Please enter your gender:(male/female)"); String TF = scan.next(); char TFChar = TF.charAt(0); System.out.println(TFChar); } }

1. Exercise 1

/* Yue Xiaopeng took the Java exam, and he and his father Yue made a promise together: If: a BMW is awarded when the score is 100; When the score is (80,99), reward an iphone xs max; Reward an iPad when your score is [60,80]; Otherwise, there is no reward at all. Please enter Yue Xiaopeng's final results from the keyboard and judge them Explain: 1.else The structure is optional. 2.For conditional expressions: ① If the relationship between multiple conditional expressions is mutually exclusive (or not intersecting), it does not matter which statement is declared above or below. ② If there is an intersection between multiple conditional expressions, you need to consider the actual situation and which structure should be declared above. ③ If there is a containment relationship between multiple conditional expressions, it is usually necessary to have declarations with a small scope above those with a large scope. Otherwise, declarations with a small scope will not have a chance to run. */ import java.util.Scanner; class IFTest02{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.println("Please enter the results of Yue Xiaopeng:"); int score = scan.nextInt(); if(score == 100){ System.out.println("Reward one BMW"); }else if(score >80 && score <=99){ System.out.println("Reward one iphone xs max"); }else if(score >= 60 && score <= 80){ System.out.println("Reward one iPad"); }else{ System.out.println("Reward? Learn!!!"); } } }

2. Exercise 2

/* Write the program: input three integers from the keyboard into variables num1, num2, num3, Sort them (using if-else if-else) and output them from small to large. */ import java.util.Scanner; class Sorting{ public static void main(String[] args){ //Scanner instantiation Scanner scan = new Scanner(System.in); System.out.println("Please enter the first integer:"); int num1 = scan.nextInt(); System.out.println("Please enter the second integer:"); int num2 = scan.nextInt(); System.out.println("Please enter the third integer:"); int num3 = scan.nextInt(); int MaxNumber = 0; if(num1 >= num2 ){ if(num3 >= num1){ System.out.println(num2 + "," + num1 + "," + num3); }else if(num3 <= num2){ System.out.println(num3 + "," + num2 + "," + num1); }else{ System.out.println(num2 + "," + num3 + "," + num1); } }else{ if(num3 >= num2){ System.out.println(num1 + "," + num2 + "," + num3); }else if(num3 <= num1){ System.out.println(num3 + "," + num1 + "," + num2); }else{ System.out.println(num1 + "," + num3 + "," + num2); } } } }

3. Exercise 3

/* My dog is five years old. How old is a five-year-old dog like a human? In fact, the first two years of a dog's life were equivalent to 10.5 years of a human being's life, and after that it increased by four years for every additional year. So how old is a 5-year-old dog equivalent to a human? It should be: 10.5 + 10.5 + 4 + 4 = 33 years old. If the user enters a negative number, display a prompt. */ import java.util.Scanner; class DogYear{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Please enter the age of the dog:"); double Dyear = scan.nextDouble(); if(Dyear <= 2 && Dyear > 0){ System.out.println("Dogs are the same age as:" + Dyear * 10.5); }else if(Dyear <= 0){ System.out.println("You entered incorrectly."); }else{ double number = 2 * 10.5 + (Dyear - 2) * 4; System.out.println("Dogs are the same age as:" + number); } } }

4. Exercise 4

/* Suppose you want to develop a lottery game where the program randomly generates a two-digit lottery ticket. Prompt the user to enter a two-digit number, and then follow the rules below to determine if the user can win. 1)If the number entered by the user matches the actual order of the lottery ticket, the bonus is $10,000. 2)If all the numbers entered by the user match all the numbers of the lottery ticket, but in different order, the bonus is $3,000. 3)If a number entered by the user matches only one number of the lottery ticket in sequence, the bonus is $1,000. 4)If a user enters a number that matches only one number of the lottery ticket out of sequence, the bonus is $500. 5)If the number entered by the user does not match any of the numbers, the lottery ticket is invalidated. Tip: Use (int) (Math.random() * 90 + 10) to generate random numbers. Math.random() : [0,1) * 90 [0,90) + 10 [10,100)[10,99] */ import java.util.Scanner; class CaiTest{ public static void main(String[] args){ //1. Randomly generate a two-digit number //System.out.println(Math.random()); //Generate [0,1) int number = (int)(Math.random()*90 + 10);//Get [10,99], that is [10,100] //System.out.println(number); int numberShi = number/10; int numberGe = number%10; //2. User enters a two-digit number Scanner input = new Scanner(System.in); System.out.print("Please enter a two-digit number:"); int guess = input.nextInt(); int guessShi = guess/10; int guessGe = guess%10; if(number == guess){ System.out.println("Bonus $10,000"); }else if(numberShi == guessGe && numberGe == guessShi){ System.out.println("Bonus $3,000"); }else if(numberShi==guessShi || numberGe == guessGe){ System.out.println("Bonus $1,000"); }else if(numberShi==guessGe || numberGe == guessShi){ System.out.println("Bonus $500"); }else{ System.out.println("No winner"); } System.out.println("The winning number is:" + number); } }

6. Exercise 5

/* Everyone knows that men should marry and women should. Then the wife's parents must marry a daughter, of course, under certain conditions: high: more than 180 cm; Rich: More than 10 million; Handsome: Yes. If all three conditions are met at the same time, then: "I must marry him!!!" If the three conditions are true, then: "Marry, not enough, more than enough." If all three conditions are not met, then: "Do not marry!" */ import java.util.Scanner; class GaoFuTest{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.println("Please enter your height:(cm)"); int height = scan.nextInt(); System.out.println("Enter your wealth:(Must)"); double weight = scan.nextDouble(); // System.out.println("Please enter if you are handsome: (true/false)"); // boolean isHandSome = scan.nextBoolean(); // if(height >= 180 && weight >= 1 && isHandSome){ // System.out.println("I must marry him!!"); // }else if(height >= 180 || weight >= 1 || isHandSome){ // System.out.println("Get married, not enough, more than enough." // }else{ // System.out.println("Don't marry!"); // } //Mode 2 System.out.println("Please enter if you are handsome: (yes or no)"); String isHandsome = scan.next(); if(height >= 100 && weight >= 1 && isHandsome.equals("yes")){ System.out.println("I must marry him!!!"); }else if(height >= 180 || weight >= 1 || isHandsome.equals("yes")){ System.out.println("Marry, not enough, more than enough."); }else{ System.out.println("Don't marry!"); } } }

2.2, Branch statement 2:switch-case structure

Note: An expression in the switch structure can only be one of the six data types: byte, short, char, int, enumeration type (JDK5.0), String type (JDK7.0)

Can't be: long, float, double, boolean.

/* Branch structure two: switch-case 1.format switch(Expression) { case Constant 1: Execute statement 1; //break; case Constant 2: Execute statement 2; //break; ... default: Execute statement n: //break; } 2.Explain: ① Match the constants in each case in turn based on the values in the switch expression. Once the match is successful, enter the corresponding case structure and execute the relevant statements. When the execution statement is invoked, the execution of other case statements continues down until the break keyword or the end is encountered. ② break, You can use a switch-case structure to indicate that once this keyword is executed, the switch-case structure is jumped out. ③ switch An expression in a structure can only be one of six data types: byte, short, char, int, enumeration type (JDK5.0), String type (JDK7.0) ④ case Constants can then be declared. Scopes cannot be declared. ⑤ break Keyword is optional. ⑥ default: Equivalent to else in if-else structure. default The structure is optional and the position is flexible. */ class SwitchTest{ public static void main(String[] args){ int number = 2; switch(number){ case 0: System.out.println("zero"); break; case 1: System.out.println("one"); break; case 2: System.out.println("twe"); break; case 3: System.out.println("three"); break; default: System.out.println("other"); break; } //********************************* //Run error, boolean type cannot be run /* boolean isHandSome = true; switch(isHandSome){ case true: System.out.println("Coke?"); break; case false: System.out.println("Chips?"); break; default: System.out.println("Error in input!!! "; } */ //********************************* String season= "summer"; switch(season) { case"spring": System.out.println(""Spring blossom"; break; case"summer": System.out.println(""Summer inflammation"; break; case"autumn": System.out.println(""Autumn is refreshing"; break; case"winter": System.out.println("Snow in winter "; break; default: System.out.println("Error in season input "; break; } //************************************** //Run error /* int age = 10; switch(age){ case age > 18: System.out.println(""Adult"; break; default: System.out.println(""Minor"; } */ } }

1. Exercise 1

/* Use switch to uppercase lower case char s. Convert only a, b, c, d, e. other output "other". Tip: String word = scan.next(); char c = word.charAt(0); switch(c) {} */ import java.util.Scanner; class SwitchCaseTest1{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); String word = scan.next(); char c = word.charAt(0); switch(c){ case 'a': System.out.println("A"); break; case 'b': System.out.println("B"); break; case 'c': System.out.println("C"); break; case 'd': System.out.println("D"); break; case 'e': System.out.println("E"); break; default: System.out.println("other"); } } }

2. Exercise 2

/* If the student's score is greater than 60, the output will be "qualified". If the score is less than 60, the output will be "unqualified". Description: If there are multiple identical statements in a switch-case statement, they can be merged. */ class SwitchTest1{ public static void main(String[] args){ int score = 78; //Scheme One switch(score / 10){ case 0: case 1: case 2: case 3: case 4: case 5: System.out.println("Unqualified"); break; case 6: case 7: case 8: case 9: case 10: System.out.println("qualified"); break; } //A better solution switch(score /60){ case 0: System.out.println("Fail"); break; case 1: System.out.println("qualified"); break; } } }

3. Exercise 3

/* Prints the season that the month belongs to, based on the month used for the specified month. 3,4,5 Spring 6,7,8 Summer 9,10,11 Autumn 12,1,2 Winter */ class MonthTest{ public static void main(String[] args){ int month = 6; switch(month){ case 12: case 1: case 2: System.out.println("winter"); break; case 3: case 4: case 5: System.out.println("Spring"); break; case 6: case 7: case 8: System.out.println("Summer"); break; case 9: case 10: case 11: System.out.println("Autumn"); break; } } }

4. Exercise 4

/* Write the program: Enter "month" and "day" of 2020 from the keyboard. The date on which the input is required to be programmed to output is the date of 2019. 2 15 : 31 + 15 5 7: 31 + 28 +31 +30 + 7 ... Note: break is optional in switch-case. */ import java.util.Scanner; class DayTest{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Please enter the 2020 month"); int month = scan.nextInt(); System.out.println("Please enter the 2020 day"); int day = scan.nextInt(); //Define a variable to hold days int sumDays = 0; switch(month){ case 12: sumDays += 30; case 11: sumDays += 31; case 10: sumDays += 30; case 9: sumDays += 31; case 8: sumDays += 31; case 7: sumDays += 30; case 6: sumDays += 31; case 5: sumDays += 30; case 4: sumDays += 31; case 3: sumDays += 29; case 2: sumDays += 31; case 1: sumDays += day; } System.out.println("2020 year" + month + "month" + day + "Day is the year's number" + sumDays + "day"); } }

5. Exercise 5

/* Enter the year, month and day from the keyboard to determine the day of the year Note: The criteria for determining whether a year is a leap year: 1)Can be divided by 4, but not by 100 or 2)Divisible by 400 (year % 4 == 0 && year % 100 != 0) || year %400 == 0) Explain: 1 Any structure that can use switch-case can be converted to if-else. Conversely, it is not established. 2.When we write branching structure, we find that we can use switch-case, [and the expression in switch does not take much value.) Can also be used, we prefer switch-case. Reason: switch-case execution is slightly more efficient. */ import java.util.Scanner; class YearDayTest{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Please enter year"); int year = scan.nextInt(); System.out.println("Please enter month"); int month = scan.nextInt(); System.out.println("Please enter day"); int day = scan.nextInt(); //Define a variable to hold days int sumDays = 0; switch(month){ case 12: sumDays += 30; case 11: sumDays += 31; case 10: sumDays += 30; case 9: sumDays += 31; case 8: sumDays += 31; case 7: sumDays += 30; case 6: sumDays += 31; case 5: sumDays += 30; case 4: sumDays += 31; case 3: //Determine whether it is a leap year if((year % 4 == 0 && year % 100 != 0) || year %400 == 0){ sumDays += 29; }else{ sumDays += 28; } case 2: sumDays += 31; case 1: sumDays += day; } System.out.println(year + "year" + month + "month" + day + "Day is the year's number" + sumDays + "day"); } }

6. Exercise 6

/* Write a program to find the corresponding Chinese Zodiac for a given year. The Chinese zodiac is based on a 12-year cycle, with one animal representing each year: rat,ox,tiger,rabbit,dragon,snake,horse,sheep,monkey,rooster,dog,pig. Tip: 2019: Pig 2019% *12 == 3 */ import java.util.Scanner; class ZodiacSignTest{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.println("Please enter a year:"); int year = scan.nextInt(); switch (year % 12){ case 1: System.out.println("rooster"); break; case 2: System.out.println("dog"); break; case 3: System.out.println("pig"); break; case 4: System.out.println("rat"); break; case 5: System.out.println("ox"); break; case 6: System.out.println("tiger"); break; case 7: System.out.println("rabbit"); break; case 8: System.out.println("dragon"); break; case 9: System.out.println("snake"); break; case 10: System.out.println("horse"); break; case 11: System.out.println("sheep"); break; case 12: System.out.println("monkey"); break; } } }
04. Cycle structure

1. Cycle structure

The ability to execute specific code repeatedly when certain conditions are met

2. Classification of Looping Statements

  • for loop
  • while loop
  • do-while loop

4.1, for cycle

Grammar Format for(①Initialization section;②Cyclic Conditional Part;④Iteration section){ ③Circulatory body part; } Execution process:①-②-③-④-②-③-④-②-③-④-.....-② Explain: ②The loop condition part is boolean Type expression when the value is false When, exit the loop ①The initialization part can declare multiple variables, but must be of the same type, separated by commas ④There can be multiple variable updates, separated by commas

/* For Use of loop structure 1. Four elements of the circular structure ① Initialization Conditions ② Cyclic condition ③ Circulatory body ④ Iteration Conditions 2. Structure of the for loop for(①;②;④){ ③ } */ class ForTest{ public static void main(String[] args){ for(int i=1;i <= 5 ;i++){ System.out.println("Hello World!"); } //Practice: int num = 1; for(System.out.print('a');num <= 3;System.out.print('c'),num++){ System.out.print('b'); } //Traverse through even numbers within 100 to get the sum of all even numbers and output the number of even numbers int sum = 0; //Record the sum of all even numbers int count = 0; for(int i = 1;i <= 100;i++){ if(i %2 == 0){ System.out.println(i); sum += i; count++; } } System.out.println("100 Sum of even numbers within:" + sum); System.out.println("Number is:" + count); } }

1. Exercise 1

/* Write a program that loops from 1 to 150 and prints a value on each line. In addition, print "foo" on every three multiplier lines. Print "biz" on multiple lines of each 5. Print out "baz" on multiple lines of each 7. */ class ForTest1{ public static void main(String[] args){ for(int i = 1;i <= 150;i++ ){ System.out.print(i + " "); if(i % 3 == 0){ System.out.print("foo "); } if(i % 5 == 0){ System.out.print("biz "); } if(i % 7 == 0){ System.out.print("baz "); } //Line Break System.out.println(); } } }

2. Exercise 2

/* Enter two positive integers m and n to find their maximum and minimum common multiples. For example, the maximum common divisor of 12 and 20 is 4 and the minimum common multiple is 60. */ import java.util.Scanner; class GnumberTest{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.println("Please enter m:"); int m = scan.nextInt(); System.out.println("Please enter n:"); int n = scan.nextInt(); //Get the larger values of m and n int max = (m > n) ? m : n; //Get the minimum values of m and n int min = (m < n) ? m : n; //greatest common factor for(int i = min;i >= 1;i--){ if(m % i == 0 && n % i == 0){ System.out.println("m and n Maximum common divisor:" + i); break; } } //Find the lowest common multiple for(int i = max;i <= m * n;i++){ if( i % m == 0 && i % n == 0){ System.out.println("m and n The lowest common multiple is:" + i); break; } } } }

3. Exercise 3

/* Output all the number of daffodils, the so-called number of daffodils refers to a three-digit number, with the number cube on each bit equal to itself. For example: 153 = 1*1*1 + 3*3 + 5*5*5 */ class ForTest2{ public static void main(String[] args){ for(int i = 100;i <= 999;i++){ int a = i / 100; //Get 100 bits int b = i % 100 /10; //Get ten digits int c = i % 10; //Get bits if(a*a*a + b*b*b + c*c*c == i){ System.out.println("This number is the number of daffodils that meet the criteria:" + i); } } } }

4.2, while cycle

Grammar Format

①Initialization section while(②Cyclic Conditional Part){ ③Circulatory body part; ④Iteration section; }

Execution process: 1-2-3-4-2-3-4-4-4-4-2-3-3-4-4-4-4-3-4-...-2

Explain:

  • Be careful not to forget to declare the fourth iteration section. Otherwise, the loop cannot end and becomes an infinite loop.
  • for and while loops can be converted to each other.
public class WhileLoop { public static void main(String args[]) { int result = 0; int i= 1; while(i<= 100) { result += i; i++; } System.out.println("result="+ result); } }

1. Exercises

/* While Use of loop structure 1. Four elements of the circular structure ① Initialization Conditions ② Cyclic condition ③ Circulatory body ④ Iteration Conditions 2. The structure of the while cycle ①Initialization section while(②Cyclic Conditions Part)] ③Circulating body part; ④Iteration section; } Execution process: 1-2-3-4-2-3-4-4-4-... -(2) Explain: 1.Be careful not to lose the iteration condition when writing a while loop. If you lose it, you may end up with a dead loop! 2.Write programs to avoid an endless loop. 3.Where a while loop can be used, a for loop can be used, and vice versa. The two can be converted to each other. Difference: for and while loops have different scopes of action in the initialization conditions section. Algorithms: Limitations. */ class WhileTest{ public static void main(String[] args){ //Traverse all even numbers within 100 int i = 1; while(i <= 100){ if(i % 2 == 0){ System.out.println(i); } i++; } } }

4.3, do-while cycle

do-while Use of loop structure 1. Four elements of the circular structure ① Initialization Conditions ② Cyclic condition --->yes boolean type ③ Circulatory body ④ Iteration Conditions 2. do-while The structure of the loop ① do{ ③; ④; }while(②); Execution process:① - ③ - ④ - ② - ① - ③ - ④ - ... - ② Explain: do-while The loop executes the loop body at least once.

1. Exercise 1

class DoWhileTest{ public static void main(String[] args){ //Traverses through all even numbers within 100 and counts the sum and even numbers of all even numbers int number = 1; int sum = 0; //Record Sum int count = 0; //Number of records do{ if(number % 2 == 0){ System.out.println(number); sum += number; count++; } number++; }while(number <= 100); System.out.println("The sum is:" + sum); System.out.println("Number is:" + count); //********************************* int numb = 10; while(numb > 10){ System.out.println("hello:while"); numb--; } int numb2 = 10; do{ System.out.println("hello: do-while"); numb2--; }while(numb2 > 10); } }

2. Exercise 2

/* Read in an indeterminate number of integers from the keyboard, determine the number of positive and negative numbers read in, and end the program when the input is 0. Explain: 1.Structures that do not limit the number of times in the loop condition section: while (true), for (true) 2.Several ways to end the loop: Mode 1: The loop condition part returns false; Mode 2: break in the loop body; */ import java.util.Scanner; class XunTest{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int Positive = 0; //Positive Number int Negative = 0; //Number of negative numbers while(true){ int number = scan.nextInt(); if(number > 0){ Positive++; }else if(number < 0){ Negative++; }else{ //Once executed, jump out of the loop. break; } } System.out.println("Number of positive numbers:" + Positive); System.out.println("Number of negative numbers:" + Negative); } }

4.4. Nested Loop Structure

1. Nested loops (multiple loops)

  • Placing one loop inside another creates a nested loop, where for, while, do...while can act as either an outer or an inner loop.
  • Essentially, nested loops are loops that treat the inner loop as the outer loop. Only when the loop condition of the inner loop is false, can the inner loop be completely jumped out, so that the outer loop can be ended and the next one can be started.
  • If the number of outer cycles is m times and the number of inner cycles is n times, the inner cyclosome actually needs to execute m*n times.

2. Examples:

  1. multiplication table
  2. All prime numbers within 100

3. Exercise 1

/* Use of nested loops 1.Nested loop: Declaring a loop structure A in the loop body of another loop structure B constitutes a nested loop 2. Outer cycle: Loop structure B Inner Cycle: Cycle Structure A 3.Explain ① An inner loop is traversed once, which is equivalent to only one execution of an outer loop body ② Suppose the outer loop needs to be executed m times and the inner loop n times. At this point, the inner loop has executed m * n times in total 4.Skill Number of outer loop control rows and inner loop control columns */ class ForForTest{ public static void main(String[] args) { //****** for(int i = 1;i <= 6;i++){ System.out.print("*"); } System.out.println();//Line Break /* ****** ****** ****** ****** */ for(int i = 1;i <= 4;i++){ for(int j = 1;j <= 6;j++){ System.out.print('*'); } System.out.println(); //Line Break } /* * ** *** **** ***** */ for(int i = 1;i <= 5;i++){ //Number of control rows for(int j = 1;j <= i;j++){ //Number of control columns System.out.print("*"); } System.out.println(); } /* ***** **** *** ** * */ for(int i = 1;i <= 6;i++){ for(int j = 1;j <= 6-i;j++){ System.out.print("*"); } System.out.println(); } /* * ** *** **** ***** **** *** ** * */ for(int i = 1;i <= 5;i++){ for(int j = 1;j <= i;j++){ System.out.print("*"); } System.out.println(); } for(int i = 1;i <= 5;i++){ for(int j = 1;j <= 5-i;j++){ System.out.print("*"); } System.out.println(); } //multiplication table for(int i = 1;i <= 9;i++){ for(int j = 1;j <= i;j++){ System.out.print(i + "*" + j + "=" + i*j + " "); } System.out.println(); //Line Break } } }

Exercise 2

/* 100 All prime numbers within Prime: A prime number, a natural number that can only be divided by 1 and itself. The minimum prime number is:2 */ class PrimeNuberTest{ public static void main(String[] args){ boolean isFlag = true; //Identity is divided, and once it is, its value is modified. for(int i = 2;i <= 100;i++){ //Traverse natural numbers within 100 for(int j =2;j < i;j++){ //j:Removed by i if(i % j == 0){ //i divides by j isFlag = false; } } if(isFlag == true){ System.out.println(i); } //Reset isFlag isFlag = true; } } }

Optimize Exercise 2

/* 100000 All prime numbers within Prime: A prime number, a natural number that can only be divided by 1 and itself. The minimum prime number is:2 */ class PrimeNuberTest{ public static void main(String[] args){ boolean isFlag = true; //Identity is divided, and once it is, its value is modified. int count = 0; //Number of recorded prime numbers //Get the current time example 1970-01-01 00:00:00 milliseconds long start = System.currentTimeMillis(); for(int i = 2;i <= 100000;i++){ //Traverse natural numbers within 100 //Optimize 2: 5447---> 11 for natural numbers that are prime themselves // For (int J =2; J < i; j++) {//j: removed by I for(int j =2;j <= Math.sqrt(i);j++){ //j:Removed by i if(i % j == 0){ //i divides by j isFlag = false; break; //Optimize 1: Only natural numbers that are not prime numbers themselves are valid. } } if(isFlag == true){ // System.out.println(i); count++; } //Reset isFlag isFlag = true; } //Get the current time example 1970-01-01 00:00:00 milliseconds long end = System.currentTimeMillis(); System.out.println("Number of prime numbers:" + count); System.out.println("The time spent is:" + (end - start)); //16843 --> 5447 Optimize One } }

Use of 4.5, break, continue

1. Use of break

  • A break statement terminates the execution of a statement block

    { ...... break; ......

}

```
  • When a break statement appears in a multi-level nested statement block, you can use a tag to indicate which level of statement block you want to terminate

    label1: { ......

label2: { ...
label3: { ...
break label2;
...
}
}
}

```

2. Use of continue

  • continue statement
    • continue can only be used in a loop structure
    • The continue statement is used to skip one execution of the loop statement block in which it resides and proceed to the next loop
    • When a continue statement appears in a multi-level nested loop body, you can indicate by tags which level of loop you want to skip

3. Use of return

  • Return: Not designed to end a loop, its function is to end a method. When a method executes a return statement, the method is ended.
  • Unlike break and continue, return directly ends the entire method, regardless of how many layers of loop it is within.

4. Description of special process control statements

  • break can only be used in switch and loop statements.
  • continue can only be used in loop statements.
  • Both functions are similar, but continue terminates the loop and break terminates the layer loop.
  • No other statement can follow break, continue, because the program will never execute the following statement.
  • A label statement must be immediately preceded by a loop. A label statement cannot be used before an acyclic statement.
  • Many languages have goto statements, which can arbitrarily transfer control to any statement in a program and execute it, but make the program prone to error. Breaks and continue s in Java are different from goto.

5. Exercise 1

/* break And the use of countinue keywords Scope of Use: Roles used in loops (differences) Same points break: switch-case End the current loop) Execution statements cannot be declared after keywords Loop structure countinue: End of current loop in loop structure Execution statement cannot be declared after keyword */ class BreakContinueTest{ public static void main(String[] args){ for(int i = 1;i <= 10;i++){ if(i % 4 == 0){ // break; //1,2,3 continue; //1,2,3,5,6,7,9,10 // System.out.println("It's time to eat!!"); } // System.out.println(i); } //******************************** for(int i = 1;i <= 4;i++){ for(int j = 1;j <= 10; j++){ if(i % 4 == 0){ // break;//Default jumps out of the loop closest to this keyword continue; } System.out.print(j); } System.out.println(); } } }

3 October 2021, 12:35 | Views: 9328

Add new comment

For adding a comment, please log in
or create account

0 comments