1. switch statement
1.1 switch sentence structure (Master)
-
format
switch (expression) { case 1: Statement body 1; break; case 2: Statement body 2; break; ... default: Statement body n+1; break; }
-
Execution process:
- First, calculate the value of the expression
- Secondly, compare with case in turn. Once there is a corresponding value, 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.
1.2 switch statement practice - spring, summer, autumn and winter (application)
- 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.
- Operation results:
Spring: 3, 4, 5 Xia: 6, 7, 8 Autumn: 9, 10, 11 Winter: 1, 2, 12
- Example code:
public class Demo1 { public static void main(String[] args) { //Enter the month data with the keyboard and receive it with variables Scanner sc = new Scanner(System.in); System.out.println("Please enter a month:"); int month = sc.nextInt(); //case penetration switch(month) { case 1: case 2: case 12: 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 you entered is incorrect"); } } }
- Note: if the case in switch does not correspond to break, case penetration will occur.
2. for loop
2.1 for loop structure (Master)
-
Cycle:
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.
-
for loop format:
for (Initialization statement;Conditional judgment statement;Conditional control statement) { Loop body statement; }
-
Format interpretation:
- 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
-
Execution process:
① Execute initialization statement
② Execute the conditional judgment statement to see whether the result is true or false
If false, the loop ends
If true, continue
③ Execute loop body statement
④ Execute conditional control statements
⑤ Go back to ② continue
2.2 for loop exercise - output data (application)
- Requirement: output 1-5 and 5-1 data on the console
- Example code:
public class ForTest01 { 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.3 for loop exercise - summation (application)
- Requirements: sum the data between 1-5, and output the sum result on the console
- Example code:
public class ForTest02 { 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 5 is completed by using the circular structure for(int i=1; i<=5; 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; /* 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; */ } //When the loop is completed, the final data is printed out System.out.println("1-5 The data and between are:" + sum); } }
- Key points of this question:
- If the requirements encountered in the future contain the word summation, please immediately think of the summation variable
- The definition position of summation variable must be outside the loop. If it is inside the loop, the calculated data will be wrong
2.4 for loop exercise - even sum (application)
- Requirements: find the even sum between 1 and 100, and output the sum result on the console}
- Example code:
public class ForTest03 { 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 summation of 1-100 is almost the same as that of 1-5, except that the end conditions are different for(int i=1; i<=100; i++) { //For the even number summation of 1-100, it is necessary to add restrictions on the summation operation to judge whether it is an even number if(i%2 == 0) { sum += i; } } //When the loop is completed, the final data is printed out System.out.println("1-100 The even sum between is:" + sum); } }
2.5 for loop exercise - daffodils (application)
- Requirement: 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
- 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
- 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
- Sample code
public class ForTest04 { 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); } } } }
2.6 for loop exercise - count the number of daffodils (application)
- Demand: count the total number of "daffodils" and output the number on the console
- Example code:
public class ForTest05 { public static void main(String[] args) { //Define the variable count, which is used to save the number of daffodils. The initial value is 0 int count = 0; //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; //In the process of determining the number of daffodils, if the conditions are met, it will not be output. Change the value of count to make count+1 if(ge*ge*ge + shi*shi*shi + bai*bai*bai == i) { count++; } } //Print out the final result System.out.println("Daffodils have:" + count + "individual"); } }
- Key points of this question:
- In the future, if the demand has statistics xxx, please think of counter variables first
- The position defined by the counter variable must be outside the loop
3. while loop
3.1 while structure (Master)
-
while loop full format:
Initialization statement; while (Conditional judgment statement) { Loop body statement; Conditional control statement; }
-
while loop execution process:
① Execute initialization statement
② Execute the conditional judgment statement to see whether the result is true or false
If false, the loop ends
If true, continue
③ Execute loop body statement
④ Execute conditional control statements
⑤ Go back to ② continue
-
Example code:
public class WhileDemo { public static void main(String[] args) { //Requirement: output "HelloWorld" 5 times on the console //for loop implementation for(int i=1; i<=5; i++) { System.out.println("HelloWorld"); } System.out.println("--------"); //while loop implementation int j = 1; while(j<=5) { System.out.println("HelloWorld"); j++; } } }
3.2 while cycle exercise - Mount Everest (application)
- 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?
- Example code:
public class WhileTest { 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"); } }
4. Cycle details
4.1 do... while loop structure (Master)
-
Full format:
Initialization statement; do { Loop body statement; Conditional control statement; }while(Conditional judgment statement);
-
Execution process:
① Execute initialization statement
② Execute loop body statement
③ Execute conditional control statements
④ Execute the conditional judgment statement to see whether the result is true or false
If false, the loop ends
If true, continue
⑤ Go back to ② continue
-
Example code:
public class DoWhileDemo { public static void main(String[] args) { //Requirement: output "HelloWorld" 5 times on the console //for loop implementation for(int i=1; i<=5; i++) { System.out.println("HelloWorld"); } System.out.println("--------"); //do...while loop implementation int j = 1; do { System.out.println("HelloWorld"); j++; }while(j<=5); } }
4.2 differences between the three cycles (understanding)
- 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 self increasing variable controlled by the conditional control statement cannot be accessed again after the for loop ends because it belongs to the syntax structure of the for loop
- The self increasing variable controlled by the conditional control statement does not belong to its syntax structure for the while loop. After the while loop ends, the variable can continue to be used
- Three schemes of dead loop (infinite loop)
- for(;😉{}
- while(true){}
- do {} while(true);
4.3 jump control statement (Master)
- Jump control statement (break)
- Jump out of the loop and end the loop
- Jump control statement (continue)
- Skip this cycle and continue with the next cycle
- Note: continue can only be used in a loop!
4.4 loop nesting (understanding)
-
Overview of loop nesting: in the loop, continue to define the loop
-
Example code:
public static void main(String[] args) { //The range of external circulation control hours and internal circulation control minutes for (int hour = 0; hour < 24; hour++) { for (int minute = 0; minute < 60; minute++) { System.out.println(hour + "Time" + minute + "branch"); } System.out.println("--------"); } }
-
understand:
- Please understand this sentence again and again (the whole inner loop is a loop body of the outer loop. If the inner loop body is not completed, the outer loop will not continue to execute downward)
-
Conclusion:
- The outer loop is executed once and the inner loop is executed once
5. Random
5.1 Random number generated by random (Master)
-
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
- Random is similar to Scanner. It is also a good API provided by Java. It internally provides the function of generating random numbers
-
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-9, 20 is written in parentheses, and the random number of parameters is 0-19
-
-
Example code:
import java.util.Random; public class RandomDemo { public static void main(String[] args) { //create object Random r = new Random(); //Get 10 random numbers with a loop for(int i=0; i<10; i++) { //Get random number int number = r.nextInt(10); System.out.println("number:" + number); } //Requirement: obtain a random number between 1 and 100 int x = r.nextInt(100) + 1; System.out.println(x); } }
5.3 Random exercise - guessing numbers (application)
-
Requirements:
The program automatically generates a number between 1-100. Use the program to guess what the number is?
When you guess wrong, give corresponding tips according to different situations
A. If the guessed number is larger than the real number, it indicates that the guessed data is larger
B. If the guessed number is smaller than the real number, it indicates that the guessed data is smaller
C. If the number you guessed is equal to the real number, you will be prompted to congratulate you on your correct guess
-
Example code:
import java.util.Random; import java.util.Scanner; public class RandomTest { 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. //Here, the if..else..if.. format is used to 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; } } } }