Java notes -- process control
1. Sequential structure
-
The basic structure in Java is sequential structure. Unless otherwise specified, it will be executed sentence by sentence in order.
-
Sequential structure is the simplest algorithm structure.
-
Between statements and between boxes, it is carried out in the order from top to bottom. It is composed of several processing steps executed in turn. It is a basic algorithm structure that any algorithm is inseparable from.
2. Select structure
-
if single selection structure
-
We often need to judge whether something is feasible before we execute it. Such a process is represented by an if statement in the program
-
Syntax: if (Boolean expression){
//The statement that will be executed if the Boolean expression is true
}
-
Use the if statement to determine whether the strings are equal:
import java.util.Scanner; public class IfDemo01 { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("Please enter the content:"); String s=scanner.nextLine(); //equals: determines whether the strings are equal if (s.equals("Hello!")){ System.out.println(s); } System.out.println("End"); scanner.close(); } }
-
-
if double selection structure
-
There are two requirements. The company wants to buy a software, pay one million yuan for success, and find someone to develop it. Such a requirement can't be solved with only one if. We need a double choice structure, so we have an if else structure
-
Syntax:
if(Boolean expression){ //The statement that will be executed if the Boolean expression is true }else{ //The statement that will be executed if the Boolean expression is false }
-
If the test score is greater than or equal to 60, you will pass, and if it is less than 60, you will fail:
import java.util.Scanner; public class IfDemo02 { public static void main(String[] args) { //If the test score is greater than or equal to 60, you will pass, and if it is less than 60, you will fail Scanner scanner = new Scanner(System.in); System.out.println("Please enter grade:"); int score = scanner.nextInt(); if (score>=60){ System.out.println("Congratulations on passing!"); }else { System.out.println("I'm sorry you failed!"); } scanner.close(); } }
-
-
if multiple selection structure
-
We found that the code just now is A little inconsistent with the actual situation. In the real situation, there may be ABCD and interval multi-level judgment. For example, 90-100 is A, 80-90 is B, etc. in life, we often choose more than two, so we need A multi-choice structure to deal with such problems!
-
Syntax: if (Boolean expression 1){
//The statement that will be executed if the value of Boolean expression 1 is true
}else if (Boolean expression 2){
//The statement that will be executed if the value of Boolean expression 2 is true
}else if (Boolean expression 3){
//The statement that will be executed if the value of Boolean expression 3 is true
}else{
//The statement that will be executed if none of the above Boolean expressions is true
}
import java.util.Scanner; public class IfDemo02 { public static void main(String[] args) { //If the test score is greater than or equal to 60, you will pass, and if it is less than 60, you will fail Scanner scanner = new Scanner(System.in); System.out.println("Please enter grade:"); int score = scanner.nextInt(); //Determine which range the input value is in if (score==100){ System.out.println("Congratulations, full marks!"); }else if (score<100 && score>=90){ System.out.println("The result is A"); }else if (score<90 && score>=80){ System.out.println("The result is B"); }else if (score<80 && score>=70){ System.out.println("The result is C"); }else if (score<70 && score>=60){ System.out.println("The result is A"); }else if (score<60 && score>=0){ System.out.println("Unfortunately, the result is unqualified!"); }else { System.out.println("Score input does not meet the specification"); } scanner.close(); } }
-
-
Nested if structure
-
It is legal to use nested if... Else statements. That is, you can use if or else if statements in another if or else if statement. You can nest else if... Else like an IF statement.
-
Syntax: if (Boolean expression 1){
//The statement that will be executed if the value of Boolean expression 1 is true
if (Boolean expression 2){
//The statement that will be executed if the value of Boolean expression 2 is true
}
}
-
Take a typical number guessing game. Guess a number between 1 and 100
import java.util.Random; import java.util.Scanner; public class IfDemo03 { public static void main(String[] args) { System.out.println("The number guessing game starts now!"); System.out.println("Please enter 1-100 Data between:"); //Randomly generate a number between 1 and 100 Random ran = new Random(); int v = ran.nextInt(100)+1; //Receive the user's input data and use the while loop to increase the playability of the game Scanner in = new Scanner(System.in); while (true){ int b = in.nextInt(); //Nested with each other if (b <= v){ System.out.println("Your guess is too large. Please continue to guess:"); }else if (b < v){ System.out.println("Your guess is too large. Please continue to guess:"); }else { System.out.println("Congratulations, you guessed right!"); System.out.println("game over"); //End cycle break; } } } }
-
-
switch multiple selection structure
-
Another implementation of the multiple selection structure is the switch case statement.
-
The switch case statement determines whether a variable is equal to a value in a series of values. Each value is called a branch.
-
Syntax:
switch(expression){ case value: //Statement break; / / optional case value: //Statement break; / / optional //You can create as many case statements as you need default: / optional //Statement }
-
public class SwitchDemo01 { public static void main(String[] args) { // char grade = 'A';//Enter a char type //Judge the above input switch (grade){ case 'A': System.out.println("excellent"); break; /*break here can be written or not, but you must pay attention to a case penetration problem If the break here is not filled in, if this string of code is executed, the next line of code will follow. Therefore, it is necessary to add a break every time a case is written to form a good habit of writing code*/ case 'B': System.out.println("good"); break; case 'C': System.out.println("pass"); break; case 'D': System.out.println("Fail"); break; default: System.out.println("excellent"); break; } } }
-
The variable types in the switch statement can be:
-
byte, short, int, or char.
-
Starting with Java SE 7
-
switch supports String type
public class SwitchDemo02 { public static void main(String[] args) { String name = "Handsome"; //JDK7 new feature, the expression result can be a string!!! //The essence of a string is still a number switch (name){ case "ugly": System.out.println("ugly"); break; case "Handsome": System.out.println("Handsome"); break; default: System.out.println("I don't understand -_—||"); } } }//Output result: handsome
-
At the same time, the case tag must be a string constant or literal.
-
-
3. Cyclic structure
-
while loop
-
The while loop is the most basic loop. Its structure is: while (Boolean expression){
//Cyclic content
}
-
As long as the Boolean expression is true, the loop will continue to execute.
-
In most cases, we will stop the loop. We need a way to invalidate the expression to end the loop.
-
In a few cases, the loop will need to be executed all the time, such as the server's request response listening, etc.
-
If the loop condition is always true, it will cause infinite loop [dead loop]. We should try our best to avoid dead loop in normal business programming, which will affect the program performance or cause the program to get stuck and crash!
-
Thinking: calculate 1 + 2 + 3 +... + 100 =?
public class WhileDemo01 { public static void main(String[] args) { //Define the initial values i and sum int i=0; int sum=0; //Cycle, sum first, and then increase automatically, otherwise the sequence will be reversed, resulting in deviation of the result while (i<=100){ sum = sum+i; i++; } System.out.println(sum); } }
-
-
do... while loop
-
For the while statement, if the condition is not met, it cannot enter the loop, but sometimes we need to execute it at least once even if the condition is not met.
-
The do... While loop is similar to the while loop, except that the do... While loop is executed at least once.
do{ // Code statement }While (Boolean expression);
-
public class DoWhlieDemo01 { public static void main(String[] args) { int i=0; int sum=0; do { sum = sum+i; i++; }while (i<=100); System.out.println(sum); System.out.println(i); } }
Although it looks the same as the while loop and the output is the same, there are still differences.
-
Differences between while and do while:
-
While judge before execute. Do while is execute before judge!
-
do... while always guarantees that the loop will be executed at least once! This is their main difference.
-
public class DoWhlieDemo01 { public static void main(String[] args) { int i=0; while(i<0){ System.out.println(i); i++; } System.out.println("====================="); do { System.out.println(i); i++; }while (i<0); } }//The output result is the while loop. The output result of the do... While loop is 0
-
-
-
for loop
-
Although all loop structures can be represented by while or do... While, Java provides another statement - for loop, which makes some loop structures simpler.
-
for loop statement is a general structure that supports iteration. It is the most effective and flexible loop structure.
-
The number of times the for loop is executed is determined before execution. The syntax format is as follows:
For (initialization; Boolean expression; update){ // Code statement }
-
Exercise 1: calculate the sum of odd and even numbers between 0-100:
public class ForDemo01 { public static void main(String[] args) { //Exercise 1: calculate the sum of odd and even numbers between 1 and 100 //Defines the initial value of an odd number int oddSum = 0; //Defines the initial value of an even number int evenSum = 0; //Enter the cycle and judge for (int i=1;i<=100;i++){ if (i%2!=0){ //Odd number oddSum+=i; }else { //even numbers evenSum+=i; } } System.out.println("Odd sum:"+oddSum); System.out.println("Even sum:"+evenSum); } }
-
Exercise 2: use the while or for statement to output numbers that can be divided by 5 between 1 and 1000, and output three numbers per line
-
for loop:
public class ForDemo02 { public static void main(String[] args) { //Exercise 2: use the while or for statement to output numbers that can be divided by 5 between 1 and 1000, and output three numbers per line for (int i = 0; i <= 1000; i++) { if (i%5==0){ System.out.print(i+"\t"); } //Let it output three per line if (i%(5*3)==10 && i!=0){ System.out.println();//To achieve line feed, these two strings of code can achieve line feed effect //System.out.print("\n"); } } } }
-
while loop:
public class WhileDemo03 { public static void main(String[] args) { //Exercise 2: use the while or for statement to output numbers that can be divided by 5 between 1 and 1000, and output three numbers per line //Define initial value int i=0; while (i<=1000){ //Determine if i can divide 5 if (i%5==0){ System.out.print(i+"\t"); } //Wrap every three values output if (i%(5*3)==10 && i!=0){ System.out.println(); } i++; } } }
-
-
Exercise 3: print the 99 multiplication table:
public class ForDemo03 { public static void main(String[] args) { /* 1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 4*1=4 4*2=8 4*3=12 4*4=16 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 * 1.First, let's print out the first column * 2.Wrap and nest the fixed 1 with a loop * 3.Remove duplicates, J < = I * 4.Adjust output style */ for (int i=1;i<=9;i++){ for (int j=1;j<=i;j++){//Remove duplicates System.out.print(j + "*" + i + "=" + (j*i) + "\t"); } System.out.println(); } } }
-
Exercise 4: Print 5 rows of triangles:
public static void main(String[] args) { //Print five lines of triangles for (int i = 0; i <= 5; i++) { for (int j = 5;j>=i;j--){ System.out.print(" "); } for (int j = 1;j<=2*i-1;j++){ System.out.print("*"); } System.out.println(); } } }
-
-
An enhanced for loop is introduced in Java 5, which is mainly used for arrays.
-
The Java enhanced for loop syntax format is as follows:
For (declaration statement: expression) { // Code sentence }
-
Declaration statement: declare a new local variable. The type of the variable must match the type of the array element. Its scope is limited to the circular statement block, and its value is equal to the value of the array element at this time.
-
Expression: an expression is the name of the array to be accessed, or a method whose return value is an array.
public class ForDemo04 { public static void main(String[] args) { int[] numbers={10,20,30,40,50};//An array is defined //Traverse array elements for (int x:numbers){ System.out.println(x); } } }
-
4,break & continue
-
Break in the body of any loop statement, you can use break to control the flow of the loop. Break is used to forcibly exit the loop without executing the remaining statements in the loop. (break statements are also used in switch statements).
-
The continue statement in the loop statement body is used to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then judge whether to execute the loop next time.
-
About goto keyword:
-
The goto keyword appears very early in program statements. Although goto is still a reserved word in Java, it has not been officially used in the language; Java has no goto. However, in the two keywords break and continue, we can still see some shadow of goto - labeled break and continue.
-
"label" refers to the identifier followed by a colon, for example: label:
-
For Java, the only place where tags are used is before loop statements. The only reason to set the label before the loop is that we want to nest another loop in it. Because the break and continue keywords usually only interrupt the current loop, but if they are used with the label, they will interrupt to the place where the label exists.
-