Learning objectives
master for,while,do...while Structure, flow and use of three circular statements master break,continue Use of keywords Master the use and jump out of nested loops Master random numbers Random Use of classes
Chapter 1 circular statements
1.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
1.2 for loop
1.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
1.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
1.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); } } }
1.3 while loop
1.3.1 syntax format
Initialization expression① while(Boolean expression②){ Circulatory body③ Step expression④ }
1.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.
1.3.3 exercise
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"); }
1.4 do... while loop
1.4.1 syntax format
Initialization expression① do{ Circulatory body③ Step expression④ }while(Boolean expression②);
1.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
1.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); }
1.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
1.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
1.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.
1.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 2 circular statement extension
2.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);
2.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); } }
2.3 nested loops
2.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(); } }
2.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 3 random numbers
3.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:
-
Import package
import java.util.Random;
-
create object
Random r = new Random();
-
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); } } }
3.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.