This is the 12th day of my participation in the August Challenge

1, program flow program control overview

Flow control statement is used to control the execution sequence of each statement in the program, which can be combined into a small logical module to complete certain functions.

Its flow control mode adopts three basic flow structures stipulated in structured programming, namely:

  • Sequential structure
  • Branching structure
  • Loop structure

1. Sequential structure

The program is executed line by line from top to bottom, without any judgment or jump.

2. Branch structure

  • Selectively execute a piece of code based on conditions.
  • There areThe if... elseandswitch-caseTwo kinds of branch statements.

3. Circular structure

  • To execute a piece of code repeatedly according to a loop condition.
  • There areWhile, do... While, forThree kinds of loop statements.
  • Note: JDK1.5 is providedforeachLoop, easy to traverse collection, array elements.

2. Sequential structure

Member variables are defined in Java using legal forward references. Such as:

3. Branch statements

3.1 Branch statement 1: if-else

1, if-else

  • Conditional expressions must be Boolean expressions (relational or logical), Boolean variables;
  • When the statement block has only one execution statement, a pair of {} can be omitted, but it is recommended to retain;
  • If-else statement structure, which can be nested as needed;
  • When the if-else structure is “multiple”, the last else is optional and can be omitted if necessary;
  • When multiple conditions are “mutually exclusive”, the order between the condition statement and the execution statement does not matter. When multiple conditions are “include”, “small up big down/child up and parent down”.

2, practice

If (conditional expression){execute expression 1}else{execute expression 2} if(conditional expression){execute expression 1}else{execute expression 2} If (conditional expression){execute expression 1}else if{execute expression 2}else if(conditional expression){execute expression 3}... Else {execute the expression n} */
class IfTest{
	public static void main(String[] args){
		/ / for example 1
		int heartBeats = 75;
		if(heartBeats < 60 || heartBeats > 100){
			System.out.println("Further tests are needed.");
		}
		System.out.println("End of inspection.");

		//举例2
		int age = 23;
		if(age < 18){
			System.out.println("You can also watch cartoons.");
		}else{
			System.out.println("You can watch tech movies now.");
		}

		/ / for example 3
		if(age < 0){
			System.out.println("The data you entered is not appropriate.");
		}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 getting into old age.");
		}else{
			System.out.println("You're a fairy."); }}}Copy the code

3.1.1. Input statements

/* To get different types of variables from the keyboard, you need to use the Scanner class steps: 1. Import java.util.Scanner; import java.util. 2. Instantiation of Scanner; 3. Call the relevant 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);

		intnum = scan.nextInt(); System.out.println(num); }}/* To get different types of variables from the keyboard, you need to use the Scanner class steps: 1. Import java.util.Scanner; import java.util. 2. Instantiation of Scanner; 3. Call the relevant 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("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);

		// The Scanner does not provide methods for retrieving a string
		System.out.println("Please enter your gender :(male/female)");
		String TF = scan.next();
		char TFChar = TF.charAt(0); System.out.println(TFChar); }}Copy the code

1

/* If you score 100 points, you will be rewarded with a BMW; An iPhone xs Max will be awarded if the score is (80,99); When the score is [60,80], an iPad will be awarded; Other times, there was no reward at all. Please input yue Xiaopeng's final grade from the keyboard and judge it. 2. For conditional expressions: ① If the relationship between multiple conditional expressions is "mutually exclusive" (or no intersection relationship), which judgment and execution statement is declared above or below, it does not matter; ② If there is an intersection relationship between multiple conditional expressions, we need to consider the actual situation according to the actual situation, and consider which structure should be declared in the above. ③ If there are containment relationships between multiple conditional expressions, it is usually necessary to declare the small range above the large range. Otherwise, small ones don't have a chance to work. * /
import java.util.Scanner;
class IFTest02{
	public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		System.out.println("Please enter Yue Xiaopeng's score:");
		int score = scan.nextInt();

		if(score == 100){
			System.out.println("Reward a BMW.");
		}else if(score >80 && score <=99){
			System.out.println("Reward an iPhone XS Max.");
		}else if(score >= 60 && score <= 80){
			System.out.println("Give me an iPad.");
		}else{
			System.out.println("Reward? Study!!"); }}}Copy the code

2

Num1, num2, num3, sort them (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 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); }}}}Copy the code

3, Practice 3

/* My dog is 5 years old. How old is a 5-year-old dog? In fact, each of the first two years of a dog's life is equivalent to 10.5 human years, and each additional year after that adds four years. So how old is a five-year-old dog? 10.5 + 10.5 + 4 + 4 + 4 = 33 years old. If the user enters a negative number, display a prompt message. * /
import java.util.Scanner;

class DogYear{
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("Please enter the dog's age:");
		double Dyear = scan.nextDouble();
		if(Dyear <= 2 &&  Dyear > 0){
			System.out.println("A dog is as old as a man:" + Dyear * 10.5);
		}else if(Dyear <= 0){
			System.out.println("Your input is incorrect.");
		}else{
			double number = 2 * 10.5 + (Dyear - 2) * 4;
			System.out.println("A dog is as old as a man:"+ number); }}}Copy the code

4, Practice 4

/* Suppose you want to develop a lottery game. The program randomly generates a two-digit lottery ticket, prompts the user to enter a two-digit ticket, and then determines whether the user can win according to the following rules. 1) If the numbers entered by the user match the actual order of the ticket, the prize is $10,000. 2) If all the numbers entered by the user match all the numbers in the lottery, but not in the same order, the prize is $3,000. 3) If a number entered by the user matches only one number in the lottery in order, the prize is $1,000. 4) If the user enters a number that matches only one of the numbers in the non-sequential case, the prize is $500. 5) If the numbers entered by the user do not match any of the numbers, the ticket is invalid. Tip: Use (int)(math.random () * 90 + 10) to generate a random number. Math. The random () : [0, 1) * 90  [0, living) + 10  [10100)  [13] 10 * /
import java.util.Scanner;

class CaiTest{
	public static void main(String[] args){
		//1. Generate a random two-digit number
		//System.out.println(Math.random()); / / to produce [0, 1)
		int number = (int)(Math.random()*90 + 10);// get [10,99], i.e. [10,100]
		//System.out.println(number);
		
		int numberShi = number/10;
		int numberGe = number%10;
		
		//2. The 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("The prize is $10,000.");
		}else if(numberShi == guessGe && numberGe == guessShi){
			System.out.println("The prize is $3,000.");
		}else if(numberShi==guessShi || numberGe == guessGe){
			System.out.println("Prize of $1,000");
		}else if(numberShi==guessGe || numberGe == guessShi){
			System.out.println("Five hundred dollars.");
		}else{
			System.out.println("Didn't win the lottery");
		}
		
		System.out.println("The winning numbers are:"+ number); }}Copy the code

6, Practice 5

/* As we all know, men should marry and women should marry. So the woman's parents want to marry her daughter, of course, to put forward certain conditions: high: above 180cm; Rich: more than 10 million; Handsome: is. If all three conditions are met, then: "I must marry him!!" If the three conditions are true, then: "Marry, less than, more than." If the 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("Please enter your wealth :(tens of millions)");
		double weight = scan.nextDouble();
// system.out. println(" please input whether 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(" marry, please. );
// }else{
// system.out. println(" not married! ") );
/ /}

		2 / / way
		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, you are better than you are.");
		}else{
			System.out.println("No!); }}}Copy the code

3.2 Branch statement 2: switch-case structure

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

Cannot be: long, float, double, Boolean.

/* execute statement 1; /* execute statement 1; //break; Case constant 2: execute statement 2; //break; . Default: execute statement n: //break; } 2. Description: ① Match constants in each case according to the value in the switch expression. Once the match is successful, enter the corresponding case structure and execute the relevant statement. When the execution statement is called, other case statements continue down until the break keyword is encountered or the end is terminated. ② the switch-case structure is broken once the keyword is executed. The expressions in the switch structure can only be one of the following six data types: byte, short, char, int, enum (JDK5.0), String (JDK7.0). Scope cannot be declared. ⑤ The break keyword is optional. ⑥ Default: equivalent to else in if-else structure. The default structure is optional and the location 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;
		}

		/ / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
		// Boolean type cannot be run
/* boolean isHandSome = true; Switch (isHandSome){case true: system.out.println (" 安 装 的?? "); ); break; Case false: system.out.println (" fries?? ") ); break; Default: system.out.println (" input error!!" ); } * /
		/ / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
		String season= "summer";
		switch(season) {
		case"spring":
			System.out.println("Spring Blossoms");
			break;
		case"summer":
			System.out.println("Summer heat.");
			break;
		case"autumn":
			System.out.println("Crisp autumn air");
			break;
		case"winter":
			System.out.println("Snow in winter");
			break;
		default:
			System.out.println("Incorrect season input.");
			break;
		}

		/ / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
		// Run error
/* int age = 10; Switch (age){case age > 18: system.out.println (" adult "); break; Default: system.out.println (" underage "); } * /}}Copy the code

04. Cycle structure

1. Circular structure

The repeated execution of a particular code function if certain conditions are met

2. Classification of loop statements

  • The for loop
  • The while loop
  • The do while loop

4.1. For Loop

Syntax formatfor(1) Initialization part; ② Part of circulation conditions; ④ Iteration part) {③ Circulation body part; } Execution process: ①-②-③-④-②-③-④-..... -② Description: ② Part of the circulation condition isbooleanType expression with a value offalse(1) The initialization part can declare multiple variables, but must be the same type, separated by commas. (4) Multiple variables can be updated, separated by commasCopy the code

/ * the use of a For loop structure, circulation structure of the four elements (1) initial conditions (2) loop condition (3) iteration loop body (4) conditions Second, the structure of the for loop for (1); (2); (4)) {3} * /
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');
		}

		// The number of even numbers up to 100 is iterated, and the sum of all even numbers is obtained
		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("Sum of even numbers up to 100:" + sum);
		System.out.println("The number is:"+ count); }}Copy the code

4.2. While Loop

Syntax format

① Initialization partwhile(② circulation condition part) {③ circulation body part; (4) Iteration; }Copy the code

Implementation process: ①-②-③-④-②-③-④-②-③-④-… – 2.

Description:

  • Do not forget to declare the iteration section ④. Otherwise, the loop cannot end and becomes an infinite loop.
  • For loops 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); }}Copy the code

4.3. The do-while loop

do-whileThe use of cyclic structure i. Four elements of cyclic structure ① initialization conditions ② cyclic conditions --> YesbooleanType ③ loop body ④ Iteration condition 2do-whileThe structure of the cycledo{(3); (4); }while(2)); Execution process: ① - ③ - ④ - ② - ① - ③ - ④ -... - ② Description:do-whileThe loop executes at least one loop body.Copy the code

4.4. Nested loop structure

1. Nested loops (multiple loops)

  • Nested loops are formed by placing one loop inside another. Where, for,while,do… While can be either an outer loop or an inner loop.
  • Essentially, a nested loop is a loop body that treats the inner loop as the outer loop. When the loop condition of the inner loop is false, the inner loop can be completely jumped out, the outer loop can be ended, and the next loop can be started.
  • If the outer loop is m times and the inner loop is N times, then the inner loop body actually needs to execute m*n times.

2.

  1. The multiplication table
  2. All primes up to 100

3, Practice 1

/* Use of nested loops 1. Nested loops: declare A loop structure A in the body of another loop structure B to form A nested loop 2. Note ① If the inner loop is executed once, the outer loop is executed only once. ② Suppose that the outer loop needs to be executed m times and the inner loop needs to be executed n times. At this time, the inner loop has executed m * N times in total
class  ForForTest{
	public static void main(String[] args) {
		/ / * * * * * *
		for(int i = 1; i <=6; i++){ System.out.print("*");
		}
		System.out.println();/ / a newline

		/* ****** ****** ****** ****** */
		for(int i = 1; i <=4; i++){for(int j = 1; j <=6; j++){ System.out.print(The '*');
			}
			System.out.println();	/ / a newline
		}
		/* *** *** **** ***** */
		for(int i = 1; i <=5; i++){// Control the number of rows
			for(int j = 1; j <= i; j++){// Control column number
				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();
		}

		// The 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();	/ / a newline}}}Copy the code

4.5. Use of break and continue

1. The use of break

  • The break statement terminates the execution of a block of statements

    {...break; . }12345
    Copy the code
  • When a break statement occurs in a multi-layer nested block, the label indicates which block to terminate

    label1:	{	......
    label2:		{	......
    label3:			{	......
    					breaklabel2; . }}}12345678
    Copy the code

2. Use of continue

  • The continue statement
    • Continue can only be used in loop structures
    • The continue statement is used to skip one execution of the block of its loop and continue to the next loop
    • When a continue statement appears in the body of a multi-level nested loop, the label indicates which layer of the loop to skip

3. Use of return

  • Return: Not specifically used to end a loop, but to end a method. When a method executes to a return statement, the method is terminated.
  • Unlike break and continue, a return directly terminates the entire method, no matter how many levels of loop the return is in.

4. Description of special process control statements

  • Break can only be used in switch statements and loop statements.
  • Continue can only be used in circular statements.
  • Both functions are similar, but continue terminates the loop and break terminates the loop.
  • There can be no other statement after break, continue, because the program never executes the following statement.
  • The labeled statement must be immediately at the head of the loop. A labeled statement cannot precede a non-loop statement.
  • Many languages have GOTO statements that transfer control at will to any statement in the program and then execute it. But make the program prone to error. Break and continue in Java are different from Goto.

5, Practice 1

/* countinue (countinue); /* countinue (countinue); /* Countinue (countinue); Cannot declare the execution statement */ after the second loop 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(" 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; // Defaults to breaking out of the loop around the closest layer of the keyword
						continue; } System.out.print(j); } System.out.println(); }}}Copy the code