If, if else, while, do while, switch and for execution statements of java

Posted by Muggin on Sun, 16 Jan 2022 01:11:38 +0100

1, java execution statement

Classification:
1. Sequential statement: the code in the method is executed from top to bottom
2. Branch statement: specify different functions according to different conditions
2.1 if branch
2.2 switch branch
3. Circular statement: if the condition is true, a function will be executed repeatedly
3.1 for loop
3.2 while loop
3.3 do while cycle
4. Special process control statements
4.1 break
4.2 continue
4.3 return
4.4 lable

1. if branch

1.1 simple if branch

Syntax structure:
If (expression){
... code block
}
Understanding: the result of an expression must be of type boolean
true - execute code block
false - jump out of if branch

Experiment 1:
import java.util.Scanner;
public class Test01{
	/**
			
		Case: if your Java test score is greater than 98,
			  You can get a Ferrari as a reward
			
	*/
	public static void main(String[] args){
		
		Scanner scan = new Scanner(System.in);
		System.out.println("Please enter your grade:");
		double score = scan.nextDouble();
		
		if(score > 98){
			System.out.println("Reward you with a Ferrari toy car");
		}
		
	}
}
Experiment 2:
import java.util.Scanner;
public class Test02{
	/**
		Knowledge points: complex if branches
		Summary:
			1.if Can judge the interval
			2.if Complex conditions can be judged
			3.Hump nomenclature of variables: except the first word, all words are capitalized
		
	*/
			
		Case: you Java If the score is more than 98 and the music score is more than 80, the teacher will reward him;
				perhaps Java If the score is equal to 100 points and the music score is greater than 70 points, the teacher can also reward him.
			Scanner scan = new Scanner(System.in);
			System.out.println("Please enter Java Achievement:");
			double javaScore = scan.nextDouble();
			System.out.println("Please enter your music score:");
			double musicScore = scan.nextDouble();
			
			if((javaScore>98&&musicScore>80) || (javaScore==100&&musicScore>70)){
				System.out.println("Reward you with a lollipop");
			}
			

	}
}

1.2 if else branch

Syntax structure:
If (expression){
... code block
}else{
... else code block
}
understand:
The result of the expression must be boolean
true - execute code block
false - execute else code block

import java.util.Scanner;
public class test3{
	//
public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		System.out.println("Please enter java Achievement:");
		double score = scan.nextDouble();
		if(score>98){
			System.out.println("Congratulations, you are qualified!!");
		}else{
			System.out.println("I'm sorry you're not qualified");
		}
	
	
	}
}

1.3. Multiple if else branches

Syntax structure:

If (expression 1){

Code block 1;

} else if (expression 2){

		 Code block 2;

} else if (expression n){

Code block n;

​ }else {

else code block;

​ }

import java.util.Scanner;
public class test3{
	/**
        Case 1: what is the value of human health
                15-20 The values in are thin
                20-25 The value within is healthy
                25-30 The value of is fat
               (Health value algorithm: weight (Kg) / height (M2)

	*/
	public static void main(String[] args){
		
		Scanner scan = new Scanner(System.in);
		System.out.println("Please enter your weight:");
		double wight = scan.nextDouble();
		System.out.println("Please enter your height:");
		double hight = scan.nextDouble();
		double health=wight/(hight*hight);
		
		if(health>15 && health<=20){
			System.out.println("Your weight is thin!!");
		}else if(health>20 && health<=25){
			System.out.println("You are in good health!!");
		}else if(health>25 && health<=30){
			System.out.println("Your body is too heavy");
		}else{
			System.out.println("Abnormal health, please go to the hospital for examination");
		}
	
	}

}

1.4 nesting of if

import java.util.Scanner;
public class Test05{
	/**
		Knowledge points: nested if branches
		
		Case: students who run within 16 seconds in the 100 meter race at the sports meeting are eligible to enter the finals,
		They were divided into men's group and women's group according to gender.
	*/
	public static void main(String[] args){
		
		Scanner scan = new Scanner(System.in);
		System.out.println("Please enter your grade:");
		double score = scan.nextDouble();
		
		if(score > 0 && score < 16){
			
			System.out.println("Please enter gender:");
			String sex = scan.next();//Input string
			if(sex.equals("male")){		//Judge whether the contents of sex and "male" are equal
				System.out.println("Congratulations on reaching the men's final");
			}else if(sex.equals("female")){//Judge whether the contents of sex and "female" are equal
				System.out.println("Congratulations on reaching the women's final");
			}else{
				System.out.println("Gender abnormality");
			}
		}else if(score >= 16){
			System.out.println("Focus on participation");
		}else{
			System.out.println("Abnormal performance");
		}
		
		/**
			Summary if:
			Syntax differences:
				if(){}: The simplest if
				if...else...:either-or
				if...else if...:Choose one more
				if It can be nested in infinite layers
			Application scenario:	
				Individual values can be judged
				Can judge the interval
				Complex conditions can be judged
		*/
		
	}
}

2. switch statement

Knowledge point: switch branch
Syntax structure:
Switch (expression){
case value 1:
... code block 1
break;
case value 2:
... code block 2
break;
case value n:
... code block n
break;
default:
... default code block
break;
}

understand:
The result of the expression can be: byte, short, int, enumeration (JDK1.5), String(JDK1.7)
Compare with value 1, value 2 and value n respectively, and execute the corresponding code block if which is equal
break: jump out of switch branch statement
The default code block is similar to else {}. It means other situations. It can be written or not according to the requirements

Extension:

1. Can case values be the same? may not
2. Can default be omitted? sure
3. Can break be omitted? sure
4. Must the default position be at the end? not always
5. Can the types of values behind case be different? It can be different, but it must be compatible
6. What can be the type of expression value? byte, short, int, enumeration (JDK1.5), String(JDK1.7)
7. Why are the types of switch expressions only byte, short, int, enumeration (JDK1.5) and String(JDK1.7)?
The result of the switch expression accepts only int at the bottom
byte is automatically converted to int
short is automatically converted to int
The enumerated object system will assign it an int value
String is the ASCII code obtained

import java.util.Scanner;
public class Test06{
	/**			
		Case:
			switch(50){
				case 10:
					System.out.println("10");
				break;
				case 50:
					System.out.println("50");
				break;
				case 100:
					System.out.println("100");
				break;
				default:
					System.out.println("...default Code block ");
				break;
			}
			System.out.println("switch Code other than branch "");
			
		Case: you participated in the computer programming competition
			If you get the first place, Maldives Tourism
			If you win the second place, you will be rewarded with an Apple Pro laptop
			If you get the third place, you will be rewarded with a mobile hard disk
			Otherwise, thank you for your participation
	*/
	public static void main(String[] args){
		
		Scanner scan = new Scanner(System.in);
		System.out.println("Please enter the competition ranking:");
		String str = scan.next();
		
		switch(str){
			case "the first":
				System.out.println("Maldives Tourism");
			break;
			case "proxime accessit":
				System.out.println("Reward apple Pro A laptop");
			break;
			case "third":
				System.out.println("Reward one mobile hard disk");
			break;
			default:
				System.out.println("Thank you for your participation");
			break;
		}	
	}
}

3. Nested if in switch statement

​ if vs switch

Differences in grammatical structure:
if expression: boolean
Expressions for switch: byte, short, int, enumeration (JDK1.5), String(JDK1.7)

Differences between application scenarios:
if: judge single value, interval and complex condition
switch: judge a single value

import java.util.Scanner;
public class test7{
	//
	/**
		Knowledge points: go deep into the switch branch
		
		Demand: enter the year and month, and output the days of the current month
		
		Leap year: a year divided by 4 and cannot be divided by 100 or 400
	*/
	public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		System.out.print("Please enter the year:\n");
		int year = scan.nextInt();
		System.out.print("Please enter month:\n");
		int month = scan.nextInt();
		int day = 0;
		switch(month){
			case 1:case 3:case 5:case 7:case 8:case 10 :case 12:
				day =31;
			break;
			case 4:case 6:case 9:case 11:
				day =30;
			break;
			case 2:
				if(year%4==0&&year%100!=0 || year%400==0){
					day=29;
				}else{
					day=28;
				}
			break;
		}
		System.out.print(year + "year" + month+"The number of days in the month is"+ day +"day");
	
	}
}

4. for loop

Knowledge points: for loop

Meaning: repeat the execution when the condition is established

Benefits: reduced code redundancy (reduced repetitive code)

Syntax structure:
For (expression 1; expression 2; expression 3){
... code block
​ }

Understanding:
Expression 1: initializing variables
Expression 2: judgment condition
Expression 3: updating variables

Execution process:
​ 1. initialize variable
​ 2. Judgment condition: the result of judgment condition must be boolean
2.1 true - execute the code block, update the variables, and repeat step 2
2.2 false - jump out of the whole loop statement

for cyclic deformation:
The scope of a variable declared in a loop can only be within a loop
There is no difference between i + + and + + i in recycling

import java.util.Scanner;
public class Test09{
	public static void main(String[] args){
	/**
			int i = 1;
			for(;i<=5;){
				System.out.println("hhhhhh");
				//i++;
				++i;
			}
			System.out.println(i);
			
		Understand case 1: output numbers 1-9
			for(int i = 1;i<=9;i++){
				System.out.println(i);
			}
			
		Understand case 2: output numbers 0-9
			for(int i = 0;i<10;i++){
				System.out.println(i);
			}
		
		Understand case 3: output odd numbers in 1 ~ 9 numbers
			//Solution 1
			for(int i = 1;i<10;i+=2){
				System.out.println(i);
			}
			//Solution 2
			for(int i = 1;i<10;i++){
				if(i%2!=0){
					System.out.println(i);
				}
			}
			
		Understand case 4: output 9 ~ 1 numbers
			for(int i = 9;i>0;i--){
				System.out.println(i);
			}
			
		Summary - understand the case: i can start from 1 or 0, and the update variable can increase or decrease
		
		Dead cycle: (should be avoided)
			for(;;){
				System.out.println("Ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha;
			}
			
		Pseudo loop: (should be avoided)
			for(int i = 0;i>=0;i++){//When the output reaches the maximum range of int type, it jumps out
				System.out.println("Ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha;
			}
			
		Case 1: circularly enter int type numbers for 5 times and output the sum
			Scanner scan = new Scanner(System.in);
			int sum = 0;//the sum
			for(int i = 1;i<=5;i++){
				System.out.println("Please enter the "+ i +" Number: ");
				int num = scan.nextInt();
				sum += num;//accumulation
			}
			System.out.println("The sum is: "+ sum";
			
		Case 2: input the scores of 5 courses of a student in a circle and calculate the average score
			Scanner scan = new Scanner(System.in);
			double sum = 0;//Total score
			for(int i = 1;i<=5;i++){
				System.out.println("Please enter the "+ i +" score: ";
				double score = scan.nextDouble();
				sum += score;//accumulation
			}
			System.out.println("The average score is: "+ (sum/5));
			
		Case 3: enter int type numbers five times in a cycle and output the maximum value
			Scanner scan = new Scanner(System.in);
		
			System.out.println("Please enter the first number: ";
			int max = scan.nextInt();//Assume that the first entered number is the maximum value
			
			for(int i = 2;i<=5;i++){
				System.out.println("Please enter the "+ i +" Number: ");
				int num = scan.nextInt();
				if(max < num){
					max = num;
				}
			}
			
			System.out.println("The maximum value is: "+ max);
			
		Case 4: printing graphics
			****
			****
			****
		*/
			for(int i = 0;i<3;i++){
				for(int j = 0;j<4;j++){
					System.out.print("*");
				}
				System.out.println();
			}
			
	}
}

4.1 for loop nesting

public class Test01{
	
	public static void main(String[] args){
		/**
			Knowledge points: for loop nesting
			
			Requirements: plotting drawings
				*
				**
				***
				****
				*****
				for(int i = 0;i<5;i++){
					for(int j = 0;j<=i;j++){
						System.out.print("*");
					}
					System.out.println();
				}

				*****
				 ****
				  ***
				   **
					*
				for(int i = 0;i<5;i++){
					for(int k = 0;k<i;k++){
						System.out.print(" ");
					}
					for(int j = 5;j>i;j--){
						System.out.print("*");
					}
					System.out.println();
				}
				
				  *
				 ***
				*****
				for(int i = 0;i<3;i++){
					for(int k = 2;k>i;k--){
						System.out.print(" ");
					}
					for(int j = 0;j<i*2+1;j++){
						System.out.print("*");
					}
					System.out.println();
				}
				
				  *
				 * *
				*****
			Scheme I:
				for(int i = 0;i<3;i++){
					for(int k = 2;k>i;k--){
						System.out.print(" ");
					}
					for(int j = 0;j<i*2+1;j++){
						if(i==0 || i==2 || j==0 || j==i*2){
							System.out.print("*");
						}else{
							System.out.print(" ");
						}
						
					}
					System.out.println();
				}
			Scheme II:
				for(int i =0;i<3;i++){
			
				switch(i){
					case 0:case 2:
					for(int k=2;k>i;k--){
						System.out.print(" ");
					}
					for(int j=0;j<2*i+1;j++){
						System.out.print("*");
					}
					break;
					case 1:
					for(int h=0;h<2;h++){
						System.out.print(" *");
					}
					break;
					}
				System.out.println();
				}
			Scheme III:
				for(int i = 0;i<3;i++){
					for(int k = 2;k>i;k--){
						System.out.print(" ");
					}
					for(int j = 0;j<i*2+1;j++){
						if(i==1&&j=i){
							System.out.print("*");
						}else{
							System.out.print(" ");
						}
						
					}
					System.out.println();
				}
			

			Demand: 99 multiplication table
		*/
				for(int i = 1;i<=9;i++){
					for(int j = 1;j<=i;j++){
						System.out.print(j + "x" + i + "=" + (i*j) + "\t");
					}
					System.out.println();
				}

		
	}
}

5. while loop

Knowledge point: while loop

Syntax structure:
While (expression){
... code block
​ }

Understanding:
The result of the expression must be boolean
true - execute code block
false - jump out of loop

Summary: the number of cycles is uncertain

public class Test02{
    public static void main(String[] args){
        
            Case: I have a dream to save 3000 yuan per month, with an increase of 1000 yuan per year. How many months later, I will save 200000 yuan
        */

            int money = 3000;
            int allMoney = 0;
            int month = 0;
            while(allMoney < 200000){
                allMoney+=money;
                month++;
                if(month % 12 == 0){
                    money+=1000;
                }
            }

        System.out.println(month + "Deposit more than 200000 months later  " + money);

      
    }
}

6. Do while loop

Knowledge point: do while loop

Syntax structure:
​ do{
... code block
} while (expression);

Understanding:
The result of the expression must be boolean
true - execute code block
false - jump out of loop

Execution sequence:
​ 1. Execute the code block first
​ 2. Judgment expression
2.1 true - execute the code block and repeat step 2
2.2 false - jump out of loop

import java.util.Scanner;
public class Test03{
	
	public static void main(String[] args){

		Scanner scan = new Scanner(System.in);
		System.out.println("Guess who the author is");
		String str;
		do{
			System.out.println("The moon shines in front of the window");
			System.out.println("It's suspected to be frost on the ground");
			str = scan.next();
		}while(str.equals("Li Bai"));
	
	}
}

7,for Vs while Vs do-while

Differences in grammatical structure:
For (initialize variable; judge condition; update variable) {}
While {}
Do{}while (judgment condition);
Loop commonality: the results of judging conditions are boolean values, true - loop, false - jump out of loop
Differences in execution order:
for: judge first and then execute
while: judge first and then execute
Do while: execute it first and then judge

Differences between application scenarios:
Determination of cycle times: for
If the number of cycles is uncertain, judge first and then execute: while
If the number of cycles is uncertain, execute it first and then judge: do while

Topics: Java JavaEE