JavaSE basics review day03

Posted by foobar on Mon, 17 Jan 2022 00:02:29 +0100

Learning objectives

1,Master keyboard entry Scanner Basic use of
2,Master three if Branch statement structure, execution process and use
3,master switch Branch statement structure, execution process and use
4,master for,while,do...while Structure, flow and use of three circular statements
5,master break,continue Use of keywords
6,Master the use and jump out of nested loops
7,Master random numbers Random Use of classes

Chapter 1 data input

Data input is program acquisition, which refers to obtaining the data entered by the user's keyboard. How to implement it in java language?

We can get the user's input through the Scanner class.

1.1 use of scanner class

1.1.1 Guide Package

Use the import keyword to import the package, import the package before all the code of the class, and introduce the type to be used, Java All classes under Lang package do not need to be imported.

Scanner class in Java Util package, so you need to import this class.

Format:

import Package name.Class name;

1.1.2 creating objects

Format:

Data type variable name  =  new data type(parameter list);

1.1.3 calling method

Format:

Variable name.Method name();

Example:

Get the integer entered by the keyboard.

import java.util.Scanner;
public class ScannerDemo {
  	public static void main(String[] args) {  		
		//create object
		Scanner sc= new Scanner(System.in);
		
		// Friendly tips
		System.out.println("Please enter an integer:");
		
		//receive data 
		int n = sc.nextInt();
		
		//output data
		System.out.println("n= " + n);
  	}
}

1.2 Scanner exercise

Requirements:

Use the keyboard to enter the scores of 90 points, 94 points and 82 points of the three students, and then use the operator to compare them to obtain the highest score and print the results.

Example:

import java.util.Scanner;
public class ScannerTest {
    public static void main(String[] args) {
        // Create keyboard entry object Scanner
        Scanner sc = new Scanner(System.in);
        
        //Keyboard input three student scores and assign them to three variables respectively.
        System.out.println("Please enter the first student grade:");
        int score1 = sc.nextInt();
        System.out.println("Please enter the second student grade:");
        int score2 = sc.nextInt();
        System.out.println("Please enter the third student grade:");
        int score3 = sc.nextInt();
        
        // Use the ternary operator to obtain the higher score values of the first two students and save them with temporary variables.
        int tempScore = score1 > score2 ? score1 : score2;
        //Use the ternary operator to obtain the temporary score value and the higher score value of the third student, and save it with the highest score variable.
        int maxScore = tempScore > score3 ? tempScore : score3;
        
        // Output results
        System.out.println("The highest scores of the three students are:" + maxScore +"branch");
    }
}

Chapter 2 branch structure

In the process of a program execution, the execution order of each statement has a direct impact on the result of the program. Therefore, we must know the execution process of each statement. Moreover, many times we need to control the execution order of statements to realize the functions we want to complete.

In Java, process control statements can be divided into the following three categories:

  • Sequential structure

  • Branch structure (if, switch)

  • Loop structure (for, while, do... while)

Among them, the so-called sequential structure, that is, after the program enters the main() method entry, it is executed from top to bottom. As follows:

// main() method entry
public static void main(String[] args){
    //Execute sequentially, and run from top to bottom according to the writing order
    System.out.println(1);
    System.out.println(2);
    System.out.println(3);
}

This sequential structure is very common, and we have used this structure in our previous exercises. However, in actual development, there may be some judgment or other factors that need to control the execution of statements, so branch structure and loop structure appear.

Next, let's explain the branch structure in detail.

2.1 if conditional branch statement

According to the actual business requirements, if conditional branch statements can be divided into the following three forms:

1,if Single branch statement

2,if...else... Double branch statement

3,if...else if ...else...Multi branch statement

The ternary operators we learned earlier can be converted using if statements.

2.1.1 if single branch statement

1. Introduction to if statement

  • Syntax format:
if(Conditional expression){
  	Statement body;
}
//Other statements
  • Pseudo code example:
if(Xiao Ming scored more than 700 points in the college entrance examination){
  	Xiao Ming can go to Harvard;
}
//Other statements
 Look at the results of others

2. if statement execution process

(1) First, the value of the conditional expression is calculated;

(2) If the value of the conditional expression is true, the statement body is executed;

(3) If the value of the conditional expression is false, the statement body will not be executed;

(4) Continue to execute other subsequent statements.

3. if statement exercise

public static void main(String[] args){
    System.out.println("start");
    // Define two variables
    int a = 10;
    int b = 20;
    //Variables are judged using if
    if (a == b){
      	System.out.println("a be equal to b");
    }
    int c = 10;
    if(a == c){
      	System.out.println("a be equal to c");
    }
    System.out.println("end");
}

2.1.2 if... else double branch statement

The above if single branch statement only cares about what happens if the condition is true. Sometimes, we care about what happens if it doesn't work. Therefore, the if... else double branch statement was born.

1. Introduction to if... else statement

  • Syntax format:
if(Conditional expression) { 
  	Statement body 1;
} else() {
  	Statement body 2;
}
//Other statements
  • Pseudo code example:
if(Xiao Ming scored more than 700 points in the college entrance examination){
  	Xiao Ming can go to Harvard;
}else{
	Xiao Ming chooses to reread it once;
}
//Other statements
 Look at the results of others

2. if... else statement execution process

(1) First, the value of the conditional expression is calculated;

(2) If the value of the conditional expression is true, execute statement body 1;

(3) If the value of the conditional expression is false, execute statement body 2;

(4) Continue to execute other subsequent statements.

3. if... else statement exercise

public static void main(String[] args) {
    System.out.println("start");
    //Define two variables
    int a = 10;
    int b = 20;
    //Requirement: judge whether a is greater than b. If yes, the value of a output on the console is greater than b; otherwise, the value of a output on the console is not greater than b
    if(a > b) {
    	System.out.println("a The value of is greater than b");
    } else {
    	System.out.println("a The value of is not greater than b");
    }
    System.out.println("end");
}

4. if... else case

  • **Requirements: * * let the user give an integer arbitrarily. Please use the program to judge whether the integer is odd or even, and output whether the integer is odd or even on the console.

  • analysis:

    ① In order to give an arbitrary integer, enter a data with the keyboard;
    ② To judge whether an integer is even or odd, there are two cases to judge, using the if... else structure;
    ③ To judge whether even numbers need to use the remainder operator to realize this function, number% 2 = = 0;
    ④ According to the judgment, the corresponding content is output on the console.

  • code implementation

public static void main(String[] args) {
    //In order to give an arbitrary integer, enter a data with the keyboard. (guide package, create object and receive data)
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter an integer:");
    int number = sc.nextInt();
    //To judge whether an integer is even or odd, there are two cases to judge. Use if Else structure
    //To judge whether even numbers need to use the remainder operator to realize this function number% 2 = = 0
    //According to the judgment, the corresponding content is output on the console
    if(number%2 == 0) {
    	System.out.println(number + "It's an even number");
    } else {
    	System.out.println(number + "It's an odd number");
    }
}

2.1.3 if... else multi branch statements

If single branch condition is to focus on how one condition is established. If... else double branch statement is to focus on how one condition is established and how it fails. In other cases, our conditions may be diverse, and we should also pay attention to different execution in different cases. Therefore, we derive the multi branch statements of if... else and if... else.

1. Introduction to if... else statement

  • Syntax format:
if (Conditional expression 1) {
  	Statement body 1;
} else if (Conditional expression 2) {
  	Statement body 2;
}
...
}else if (Conditional expression n) {
 	Statement body n;
} else {
  	Statement body n+1;
}
//Other statements
  • Pseudo code example
if(Xiao Ming scored more than 700 points in the college entrance examination){
  	Xiao Ming can go to Harvard;
}else if(Xiao Ming's college entrance examination score is more than 600, but not more than 700){
	Xiao Ming chooses to go to Wuhan University;
} 
else {
	// I didn't even get 600 points
	Xiao Ming really reread it;
}
//Other statements
 Look at the results of others

2. If... else if... else execution process

(1) First, the value of conditional expression 1 is calculated to determine whether the result is true or false;

(2) If true, execute statement body 1, and then execute other statements at the bottom;

(3) If it is false, continue to evaluate conditional expression 2 to judge whether the result is true or false;

(4) If true, execute statement body 2, and then execute other statements at the bottom;

(5) If it is false, continue to evaluate the conditional expression... To judge whether the result is true or false;

(6) ...

(7) If no conditional expression is true, the statement body n+1 in else is executed.

3. If... else if... else exercise

Enter a week (1, 2,... 7) on the keyboard and output the corresponding Monday, Tuesday,... Sunday

  • Input 1 output Monday
    Input 2 output Tuesday
    Input 3 output Wednesday
    Input 4 output Thursday
    Input 5 output Friday
    Input 6 output Saturday
    Input 7 output Sunday
  • Input other digital output digital error.
public static void main(String[] args) {
    System.out.println("start");
    // Requirement: enter a week (1,2,... 7) on the keyboard, and output the corresponding Monday, Tuesday Sunday
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter a number of weeks(1~7): ");
    int week = sc.nextInt();
    if(week == 1) {
    	System.out.println("Monday");
    } else if(week == 2) {
    	System.out.println("Tuesday");
    } else if(week == 3) {
    	System.out.println("Wednesday");
    } else if(week == 4) {
    	System.out.println("Thursday");
    } else if(week == 5) {
    	System.out.println("Friday");
    } else if(week == 6) {
    	System.out.println("Saturday");
    } else if(week == 7) {
    	System.out.println("Sunday");
    } else {
    	System.out.println("Wrong number!");
    }
    System.out.println("end");
}

4. if... else case

  • Demand: Xiaoming is about to take the final exam. Xiaoming's father told him that he will give him different gifts according to his different test scores. If you can control Xiaoming's score, please use the program to realize what kind of gift Xiaoming should get and output it on the console.

  • Reward rules:

    One 95 ~ 100 mountain bike
    Play once in 90 ~ 94 amusement parks
    One 80 ~ 89 transformers toy
    Beat the fat under 80

  • analysis:

    (1) Xiao Ming's test score is unknown. You can use the keyboard to obtain the value;

    (2) Because there are many kinds of awards, they belong to a variety of judgments, which are implemented in the format of if... else if... else;

    (3) Set corresponding conditions for each judgment;

    (4) Set corresponding rewards for each judgment.

  • code implementation

public static void main(String[] args) {
    //Xiao Ming's test score is unknown. You can use the keyboard to get the value
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter a score:");
    int score = sc.nextInt();
    //Because there are many kinds of rewards, they belong to a variety of judgments. If else if... Else format implementation
    //Set the corresponding conditions for each judgment
    //Set corresponding rewards for each judgment
    //Data test: correct data, boundary data, error data
    if(score>100 || score<0) {
    	System.out.println("The score you entered is incorrect");
    } else if(score>=95 && score<=100) {
    	System.out.println("One mountain bike");
    } else if(score>=90 && score<=94) {
    	System.out.println("Play in the playground once");
    } else if(score>=80 && score<=89) {
    	System.out.println("A transformer toy");
    } else {
    	System.out.println("Fat beat");
    }
}

2.2 switch select branch statement

In the previous section, we handled the weeks entered by the user and the student's grades using the multi conditional branch statement if... else if... else. In each condition judgment, you need to execute an expression statement to judge whether it is true. In addition, Java provides a more convenient multi conditional branch statement switch.

2.2.1 switch introduction

  • switch statement format:
switch(expression) {
  case Constant value 1:
    Statement body 1;
    break;
  case Constant value 2:
    Statement body 2;
    break;
  ...
  default:
    Statement body n+1;
    break;
}
  • Pseudo code example
switch(1) {
  case 1:
    It's Monday;
    break;
  case 2:
    It's Tuesday;
    break;
  ...
  default:
    The number of weeks you entered is not valid!;
    break;
}

2.2.2 switch execution process

  • First, calculate the value of the expression;
  • Then, compare the case from top to bottom. Once there is a corresponding value match, the corresponding statement will be executed, and the break will end in the process of execution.
  • Finally, if all case s do not match the value of the expression, the body of the default statement is executed, and the program ends.

2.2.3 switch exercise

  • switch statement practice - spring, summer, autumn and winter

    • Demand: there are 12 months in a year, belonging to four seasons: spring, summer, autumn and winter. Enter a month on the keyboard. Please use the program to judge which season the month belongs to and output it.

    • Demonstration effect

      Input: 1, 2, 12 output: Winter

      Input: 3, 4, 5 Output: Spring

      Input: 6, 7, 8 output: Summer

      Input: 9, 10, 11 output: Autumn

      Input: other digital output: digital error

  • code implementation

public static void main(String[] args) {
    //Define month variables and judge seasons
    int month = 6;
    //switch statement implementation selection
    switch(month) {
        case 1:
            System.out.println("winter");
            break;
        case 2:
            System.out.println("winter");
            break;
        case 3:
            System.out.println("spring");
            break;
        case 4:
            System.out.println("spring");
            break;
        case 5:
            System.out.println("spring");
            break;
        case 6:
            System.out.println("summer");
            break;
        case 7:
            System.out.println("summer");
            break;
        case 8:
            System.out.println("summer");
            break;
        case 9:
            System.out.println("autumn");
            break;
        case 10:
            System.out.println("autumn");
            break;
        case 11:
            System.out.println("autumn");
            break;
        case 12:
            System.out.println("winter");
            break;
        default:
            System.out.println("The month number you entered is incorrect!");
            break;
    }
}

**Note: * * in the switch statement, the data types of expressions can be byte, short, int, char, enum (enumeration class, JDK5 starts to support), String (String, JDK7 starts to support).

2.2.4 case penetration

In the switch statement, if break is not written after the case, penetration will occur, that is, it will not judge the value of the next case and run directly backward until a break is encountered or the overall switch ends.

public static void main(String[] args) {
    //Define month variables and judge seasons
    int month = 6;
    //switch statement implementation selection
    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;
        default:
            System.out.println("The month number you entered is incorrect");
            break;
    }
}

Chapter III circular statements

3.1 cycle overview

In actual development, there may be a function that requires us to judge the size of two data, or the current season, and other similar requirements. We can use the if and switch conditional statements just learned earlier for control processing.

However, we may also encounter the following requirements: we are required to calculate the sum of 1 ~ 100, or to be more straightforward, we are required to print 1000 lines of helloword. This kind of work that needs to be repeated many times needs to be handled with another circular statement of Java.

A loop statement can repeatedly execute a piece of code when the loop conditions are met. This repeatedly executed code is called a loop body statement. When the loop body is repeatedly executed, the loop judgment condition needs to be modified to false at an appropriate time to end the loop, otherwise the loop will be executed all the time and form a dead loop.

Java loop statement classification:

  • for loop
  • while Loop
  • do... while loop
  • Nested loop

3.2 for loop

3.2.1 syntax format

for(Initialization expression①; Boolean expression②; Step expression④){
		Circulatory body③
}

explain:

  • Initialization statement: used to indicate the starting state when the loop is opened. In short, it is what it looks like when the loop starts
  • Condition judgment statement: used to indicate the condition of repeated execution of the loop. In short, it is used to judge whether the loop can be executed all the time
  • Loop body statement: used to represent the content of loop repeated execution, which is simply the matter of loop repeated execution
  • Conditional control statement: used to represent the contents of each change in the execution of the loop. In short, it controls whether the loop can be executed

3.2.2 execution process

  • Execution sequence: ① ② ③ ④ > ② ③ ④ > ② ③ ④... ② not satisfied.
  • ① Responsible for completing the initialization of loop variables
  • ② It is responsible for judging whether the cycle conditions are met. If not, it will jump out of the cycle
  • ③ Executed statement
  • ④ After the cycle, the change of variables involved in the cycle conditions

3.2.3 practice

1. Output data of 1-5 and 5-1 on the console

public static void main(String[] args) {
    //Requirements: output data 1-5
    for(int i=1; i<=5; i++) {
    	System.out.println(i);
    }
    System.out.println("--------");
    //Requirements: output data 5-1
    for(int i=5; i>=1; i--) {
   		System.out.println(i);
    }
}

2. Sum the data between 1 and 100, and output the sum result on the console

public static void main(String[] args) {
    //The final result of summation must be saved. You need to define a variable to save the summation result. The initial value is 0
    int sum = 0;
    //The data from 1 to 100 is completed by using the circular structure
    /*
        sum += i; sum = sum + i;
        The first time: sum = sum + i = 0 + 1 = 1;
        The second time: sum = sum + i = 1 + 2 = 3;
        The third time: sum = sum + i = 3 + 3 = 6;
        The fourth time: sum = sum + i = 6 + 4 = 10;
        The fifth time: sum = sum + i = 10 + 5 = 15;
        . . . 
        */
    for(int i=1; i<=100; i++) {
        //Write repeated things into the loop structure
        // The iterative thing here is to add the data i to the variable sum used to hold the final summation
        sum += i;        
    }
    System.out.println(sum);
}
  • Key points of this topic

    • If the requirements encountered in the future contain the word summation, please think of summation variables immediately;

    • The definition position of summation variable must be outside the loop. If it is inside the loop, the calculated data will be wrong.
         
       
      3. Output all "daffodils" on the console

  • Explanation: what is daffodil number?

    • Narcissus number refers to a three digit number. The sum of the number cubes of one digit, ten digit and hundred digit is equal to the original number
    • For example, 153 3 * 3 * 3 + 5 * 5 * 5 + 1 * 1 * 1 = 153
  • Idea:

    • Obtain all three digits for filtering. The minimum three digits are 100 and the maximum three digits are 999. Use the for loop to obtain
    • Get the bits, tens and hundreds of each three digit number, and make an if statement to judge whether it is the number of daffodils
public static void main(String[] args) {
    //The output of all daffodils must be used to cycle through all three digits, starting from 100 and ending at 999
    for(int i=100; i<1000; i++) {
        //Gets the value on each of the three digits before calculation
        int ge = i%10;    
        int shi = i/10%10;
        int bai = i/10/10%10;
        //The judgment condition is to take out each value in the three digits, calculate the cube sum, and compare it with the original number
        if(ge*ge*ge + shi*shi*shi + bai*bai*bai == i) {
        	//The number satisfying the output condition is the number of daffodils
        	System.out.println(i);
        }        
    }    
}

3.3 while loop

3.3.1 syntax format

Initialization expression①
while(Boolean expression②){
    Circulatory body③
    Step expression④
}

3.3.2 execution process

  • Execution sequence: ① ② ③ ④ > ② ③ ④ > ② ③ ④... ② not satisfied.
  • ① Responsible for completing the initialization of loop variables.
  • ② It is responsible for judging whether the cycle conditions are met. If not, it will jump out of the cycle.
  • ③ Specific executed statements.
  • ④ After the cycle, the change of the cycle variable.

3.3.3 practice

1. Height of Mount Everest

  • Demand: the highest mountain in the world is Mount Everest (8844.43m = 8844430mm). If I have a large enough paper, its thickness is 0.1mm. How many times can I fold it to the height of Mount Everest?

  • Idea:

    • Define counter variables ready for counting times
    • Define the thickness of the paper and the height of Mount Everest. Pay attention to unit conversion
    • Write the judgment conditions for the while cycle. When the paper thickness is less than or equal to the height of Mount Everest, it indicates that the cycle can continue, and the paper inside the cycle * = 2
    • After each folding in the cycle, the counter will increase once, and the counter will be printed after the cycle
 public static void main(String[] args) {
		//Define a counter with an initial value of 0
		int count = 0;		
		//Define paper thickness
		double paper = 0.1;		
		//Defines the height of Mount Everest
		int zf = 8844430;		
		//Because you need to fold repeatedly, you need to use a loop, but you don't know how many times to fold. In this case, it is more suitable to use a while loop
		//The folding process stops when the paper thickness is greater than Everest, so the requirement to continue is that the paper thickness is less than Everest height
		while(paper <= zf) {
			//During the execution of the cycle, the thickness of the paper shall be doubled each time the paper is folded
			paper *= 2;			
			//How many times is the accumulation performed in the loop folded
			count++;
		}		
		//Print counter value
		System.out.println("Folding required:" + count + "second");
}

3.4 do... while loop

3.4.1 syntax format

Initialization expression①
do{
    Circulatory body③
    Step expression④
}while(Boolean expression②);

3.4.2 execution process

  • Execution sequence: ① ③ ④ > ② ③ ④ > ② ③ ④... ② not satisfied.
  • ① Responsible for completing the initialization of loop variables.
  • ② It is responsible for judging whether the cycle conditions are met. If not, it will jump out of the cycle.
  • ③ Executed statement
  • ④ Changes of cyclic variables after cycling

3.4.3 practice

1. Output HelloWorld 10 times on the console

public static void main(String[] args) {
    int x=1;
    do {
      System.out.println("helloworld");
      x++;
    }while(x<=10);
}

Characteristics of do... while loop: unconditionally execute the loop body once. Even if we directly write the loop condition as false, it will still loop once. Such a loop has certain risks, so beginners are not recommended to use the do... while loop.

public static void main(String[] args){
    do{
      	System.out.println("Unconditional execution once");
    }while(false);
}

3.5 summary of three loop statements

  • The difference between the three cycles

    • for loop and while loop first judge whether the condition is true, and then decide whether to execute the loop body (judge first and then execute)
    • The do... while loop executes the loop body once, and then judges whether the condition is true and whether to continue to execute the loop body (execute first and then judge)
  • The difference between a for loop and a while loop

    • The for loop is used to control the number of iterations when the number of cycles is known;

    • while and do... while loops can also be used when the number of loops is unknown.

  • Summary of the differences between the three cycles

    1. Suggested order: for, while, do while
    2. If the number of cycles is certain, it is recommended to use for. If the number of cycles is uncertain, it is recommended to use while
    3. The do while loop is executed at least once

3.6 jump out statement

In the process of using circular statements, there may be the following scenario. We want to find each student in a class and find the person whose name is "Zhang San" (if there is no duplicate name in the class).

If you use the previous loop traversal method, you will loop each student and compare the names. There is a problem. For example, there are 100 students who have just found the third one. Is it necessary to continue to find it?

Therefore, similar requirements require us to control that a point in the loop structure jumps out of the current statement.

Jump out statement keyword:

  • break
  • continue

3.6.1 break

1. Usage scenario

  • In the select structure switch statement
  • In a loop statement

2. Function

  • Jump out of the current entire loop statement.

3.6.2 continue

1. Usage scenario

  • In a loop statement

2. Function

  • End this cycle and enter the next cycle.

**Exercise: * * observe the execution results of the following code and analyze the functions of break and continue

public static void main(String[] args) {
    for (int i = 1; i<=10; i++) {
       
        if(i % 3 == 0){
          //Open the comments separately to see the execution results
          //break;  
          //continue; 
        }
        System.out.println("i= "+i);
    }
}

Chapter 4 circular statement extension

4.1 dead cycle

  • **Dead loop: * * that is, the condition in the loop is always true, and the dead loop is a loop that never ends. For example: while(true) {}.

In the later development, there will be scenes of using an endless loop. For example, we need to read the input entered by the user, but we don't know how much data the user inputs, and we can only use an endless loop. When the user doesn't want to input data, the loop can be ended. How to end an endless loop, we need to use the jump out statement.

  • Three schemes of dead loop (infinite loop)

    • for(;😉{}
    • while(true){}
    • do {} while(true);

4.2 variation cycle

When we introduced the for loop earlier, we introduced the for loop of standard syntax:

for(Initialization expression①; Boolean expression②; Step expression④){
		Circulatory body③
}

In addition, the for loop has some variant syntax:

Initialization expression①
for(; Boolean expression②; ){
		Circulatory body③
		Step expression④
}

In other words, the initialization expression of the for loop can be placed before the for loop statement as a global variable; Step expression ④ can be placed in braces of for loop statement {}.

Examples are as follows:

	public static void main(String[] args) {
	    //Requirements: output data 1-5
		int i=1;
	    for(; i<=5;) {
	    	System.out.println(i);
	    	i++;
	    }
	}

In addition, the initialization representation and layout expression in the for loop support multiple declarations at the same time.

public static void main(String[] args) {
    for(int i=0,j=5; i<=5&&j>3;i++,j--) {
    	System.out.println("i= "+i+",j= "+j);
    }
}

4.3 nested loops

4.3.1 nested recycling

The so-called nested loop means that the loop body of one loop is another loop. For example, there is also a for loop in the for loop, which is a nested loop. Total number of cycles = number of external cycles * number of internal cycles.

Nested loop format:

for(Initialization expression①; Cycle condition②; Step expression⑦) {
    for(Initialization expression③; Cycle condition④; Step expression⑥) {
      	Execute statement⑤;
    }
}

Nested loop execution process:

  • Execution sequence: ① ② ③ ④ ⑤ ⑥ > ④ ⑤ ⑥ > ⑦ ② ④ ⑤ ⑥ > ④ ⑤ ⑥

  • One external circulation and multiple internal circulation (one circle).

  • For example, the relationship between the calendar and the month, and the relationship between minutes and seconds in the clock

    • For example, from 2020 to 2023, a total of 3 years, 12 months a year. Among them, the year is regarded as an external cycle and the month as an internal cycle.

Exercise: use nested loops to print the months from 2021 to 2023 in the format of xxxx year x month.

public static void main(String[] args) {
    //Print months from 2020 to 2023
    //Year is external circulation, 3 years; Month is internal circulation, December
    for (int i = 2020; i <= 2023; i++) {
        for (int j = 1; j <= 12; j++) {
            //Print asterisks without line breaks
            System.out.print(i + "year" + j + "month ");
        }
        //After 12 months of internal circulation printing, a line feed is required
        System.out.println();
    }
}

**Case: * * print a 99 multiplication table.

	public static void main(String[] args) {
	    //Outer loop control line
	    for (int i = 1; i <= 9; i++) {
	    	// Inner loop control column
	        for (int j = 1; j <= i; j++) {
	            //No line breaks \ t indicates tabs
	            System.out.print(i + "*" + j + "="+i*j+"\t");
	        }
	        // A line break is required
	        System.out.println();
	    }
	}

4.3.2 nested loop jump out

In the previous section, the break and continue keywords are used to jump out of a single loop. If you are in a nested loop, do these two keywords take effect? At the same time, what if you want to jump out of the outer loop?

To jump out of the specified outer loop in a nested loop, use the following methods:

alias: for(Initialization expression①; Cycle condition②; Step expression⑦) {
    for(Initialization expression③; Cycle condition④; Step expression⑥) {
      	Execute statement⑤;
      //	break alias;
      	continue alias;
    }
}

As shown above, break and continue jump out of the current loop statement by default. In a nested loop, if you want to jump out of an outer loop, you need to specify an alias for the outer loop first, and then follow the alias of the jump out loop after break and continue.

Example:

	public static void main(String[] args) {
	    //Outer loop control line
	   a: for (int i = 1; i <= 9; i++) {
	    	// Inner loop control column
	        for (int j = 1; j <= i; j++) {
	        	if(j>=5) {
	        		break a;
	        	}
	            //No line breaks \ t indicates tabs
	            System.out.print(i + "*" + j + "="+i*j+"\t");
	        }
	        // A line break is required
	        System.out.println();
	    }
	}

Chapter 5 random numbers

5.1 introduction to random

  • summary:

    • Random is similar to Scanner. It is also a good API provided by Java. It internally provides the function of generating random numbers
    • API follow-up courses are explained in detail. Now it can be simply understood as the code written in Java
  • Use steps:

    1. Import package

      import java.util.Random;

    2. create object

      Random r = new Random();

    3. Generate random number

      int num = r.nextInt(10);

      Explanation: 10 represents a range. If 10 is written in parentheses, the generated random number is 0 (including) - 9 (including), 20 is written in parentheses, and the random number of parameters is 0 (including) - 19 (including)

  • Use the Random class to complete the operation of generating three Random integers within 10. The code is as follows:

//1. Guide Package
import java.util.Random;
public class RandomDemo1 {
  	public static void main(String[] args) {
        //2. Create random number object
        Random r = new Random();

        for(int i = 0; i < 3; i++){
            //3. Randomly generate a data
            int number = r.nextInt(10);
            //4. Output data
            System.out.println("number:"+ number);
        }		
    }
}

5.2 Random exercise

  • **Requirements: * * the program automatically generates a number between 1 and 100. Use the program to guess what the number is? forty-nine

  • effect:

    • If the guessed number is larger than the real number, it indicates that the guessed data is larger
    • If the guessed number is smaller than the real number, it indicates that the guessed data is smaller
    • If the guessed number is equal to the real number, the prompt congratulates you on your guess
  • code implementation

import java.util.Random;
import java.util.Scanner;
public class RandomDemo2 {
    public static void main(String[] args) {
        //To complete the number guessing game, you first need to have a number to guess, and use a random number to generate the number, ranging from 1 to 100
        Random r = new Random();
        int number = r.nextInt(100) + 1;
        while(true) {
            //Use the program to guess numbers. You have to enter the guessed number value every time. You need to enter it with the keyboard
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter the number you want to guess:");
            int guessNumber = sc.nextInt();
            //To compare the input numbers with the system generated data, you need to use branch statements.
            //Use if else.. if.. Format, guess according to different situations, and the result is displayed
            if(guessNumber > number) {
            	System.out.println("You guessed the number" + guessNumber + "Big");
            } else if(guessNumber < number) {
            	System.out.println("You guessed the number" + guessNumber + "Small");
            } else {
            	System.out.println("Congratulations on your guess");
            	break;
            }
        }
    }
}

Extension:

Determination of specific numbers in nextInt(100) method:

13—21 nextInt(8)+13

37 ~ 79 including head but not tail; nextInt(m-n)+n

37 ~ 79 include head and tail; nextInt(m-n+1)+n

**Summary: * * numbers between N and m (including N and excluding m), nextInt(m-n)+n.

**Note: * * add 1 when the number is included.

**More related exercises:** https://www.doc88.com/p-497273660442.html , some may have problems.

Topics: Eclipse