Java basic syntax
1. Process control statement
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 be clear about the execution process of each statement. Moreover, we often need to control the execution order of statements to achieve the functions we want.
1.1 process control statement
Sequential structure
Branch structure (if, switch)
Loop structure (for, while, do... while)
1.2 sequential structure
Sequential structure is the simplest and most basic process control in the program. There is no specific syntax structure. It is executed in sequence according to the sequence of codes. Most codes in the program are executed in this way.
Sequential structure execution flow chart:
1.3 branch structure: if statement
if statement format 1
Format: if (Relational expression) { Statement body; }
Execution process:
① First, evaluate the value of the relationship expression
② If the value of the relational expression is true, the statement body is executed
③ If the value of the relational expression is false, the statement body is not executed
④ Continue to execute the following statements
Example:
public class IfDemo { public static void main(String[] args) { System.out.println("start"); //Define two variables int a = 10; int b = 20; //Demand: judge whether the values of a and b are equal. If they are equal, output on the console: A is equal to b if(a == b) { System.out.println("a be equal to b"); } //Demand: judge whether the values of a and c are equal. If they are equal, output on the console: A is equal to c int c = 10; if(a == c) { System.out.println("a be equal to c"); } System.out.println("end"); } }
if statement format 2
Format: if (Relational expression) { Statement body 1; } else { Statement body 2; }
Execution process:
① First, evaluate the value of the relationship expression
② If the value of the relationship expression is true, execute statement body 1
③ If the value of the relationship expression is false, execute statement body 2
④ Continue to execute the following statements
Example:
public class IfDemo02 { public static void main(String[] args) { System.out.println("start"); //Define two variables int a = 10; int b = 20; b = 5; //Demand: 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"); } }
if statement case: odd even number
Requirement: if an integer is given 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, use the keyboard to enter a data
② to judge whether an integer is even or odd, you should judge it in two cases, 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, output the corresponding content on the console
import java.util.Scanner; public class IfTest01 { 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"); } } }
if statement format 3
Format: if (Relationship expression 1) { Statement body 1; } else if (Relational expression 2) { Statement body 2; } ... else { Statement body n+1; }
Execution process:
① First, evaluate the value of relationship expression 1
② If the value is true, execute statement body 1; If the value is false, the value of relationship expression 2 is evaluated
③ If the value is true, execute statement body 2; If the value is false, the value of relationship expression 3 is evaluated
④...
⑤ If no relational expression is true, the statement body n+1 is executed.
Example: enter a week (1,2,... 7) on the keyboard and output the corresponding Monday, Tuesday,... Sunday
import java.util.Scanner; public class IfDemo03 { public static void main(String[] args) { System.out.println("start"); // Requirement: enter a week number (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 { System.out.println("Sunday"); } System.out.println("end"); } }
if statement format 3 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.
analysis:
① Xiao Ming's test score is unknown. You can use the keyboard to get the value
② because there are many kinds of awards, they belong to a variety of judgments, which are realized in the format of if... else... If
③ set corresponding conditions for each judgment
④ set corresponding rewards for each judgment
1.4 branch structure: switch statement
switch statement structure
-
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.
switch statement practice - spring, summer, autumn and winter
- Demand: there are 12 months in a year, which belong to four seasons: spring, summer, autumn and winter. Enter a month with the keyboard. Please use the program to judge which season the month belongs to and output it.
- Operation results:
Spring: 3, 4, 5 Summer: 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.
1.5 cycle structure: for cycle
for Loop Structure
-
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 indicate the content of loop repeated execution, which is simply the matter of loop repeated execution
- Conditional control statement: used to indicate 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 statement
⑤ Go back to ② continue
for loop exercise - output data
- Requirement: output 1-5 and 5-1 data on the console
- Example code:
public class ForTest01 { public static void main(String[] args) { //Demand: 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); } } }
for loop exercise - sum
- Requirements: sum the data between 1-5 and output the summation results 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 data i to the variable sum used to hold the final summation sum += i; /* sum += i; sum = sum + i; 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 cycle 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 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
for loop exercise - sum even numbers
- 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 cycle is completed, the final data is printed out System.out.println("1-100 The even sum between is:" + sum); } }
for loop exercise - daffodils
- 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 and prepare for filtering. The minimum three digits are 100 and the maximum three digits are 999. Use the for loop to obtain
- Get the number of 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 to see whether it is equal if(ge*ge*ge + shi*shi*shi + bai*bai*bai == i) { //The number that meets the conditions is the number of daffodils System.out.println(i); } } } }
for loop exercise - count the number of daffodils
- 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 no longer 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
1.6 cycle structure: while cycle
while structure
-
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 statement
⑤ 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++; } } }
while cycle exercise - 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?
- 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; //Define 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 the height of Everest while(paper <= zf) { //During the execution of the cycle, each time the paper is folded, the thickness of the paper should be doubled 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.7 cycle structure: do while cycle
do... while loop structure
-
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 statement
④ 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); } }
1.8 differences between the three cycles
- 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)
- 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 for loop and while
- 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 formats of dead loop (infinite loop)
1. for(;;){} 2. while(true){} 3. do {} while(true);
1.9 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!
1.10 loop nesting
-
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
1.11 Random
Random generates random numbers
-
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 random number generated 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); } }
Random exercise - guess numbers
-
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 game of guessing numbers, you first need to have a number to guess, and use random numbers 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 use the keyboard to enter it Scanner sc = new Scanner(System.in); System.out.println("Please enter the number you want to guess:"); int guessNumber = sc.nextInt(); //Comparing the input numbers with the system generated data requires the use of 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; } } } }
If there are deficiencies, please give more advice,
To be continued, keep updating!
Let's make progress together!