Java program logic control (sequence, branch, loop)

In the process of program development, there will be three kinds of program logic: sequence structure, branch structure and loop structure.

Sequential structure means that all programs are executed in sequence according to the defined code sequence.

1.if branch structure

The if branch structure is mainly for branch operations for judgment processing of relational expressions. There are three main forms of use for branch statements. The keywords used are our if and else.

(1) if (Boolean expression) {//Single condition judgment

}

(2) if (Boolean expression) {//Single condition judgment

}else{

}

(3) if (Boolean expression) {//Multi-condition judgment

}else if (Boolean expression){

}else if (Boolean expression)...

2.switch branch structure

An if statement solves the flow control problem of the two-way branch formed by judging based on one condition. If there are more than two conditions, multiple if statements must be used to achieve the required functions, but the structure is unclear and not concise. At this time, the switch statement can be used to determine the multiple branch flow of the control program according to the value of the expression. The format of the switch statement is as follows:

public class Hello{
	public static void main(String args[]){
		int x=5;
		String str;
		switch(6){
			case 1:str="1";break;//追加break执行完一个case之后,语句就跳出switch语句
			case 2:str="2";break;
			case 3:str="3";break;
			case 4:str="4";break;
			case 5:str="5";break;
			default:str="你好!";/*如果switch中的表达式再case中没有匹配的,则执行default之后的语句*/
		}
		System.out.println("str="+str);
	}
}

Note: In the switch statement, the data types of expressions and expression constants can only be integer or character types, not Boolean types.

3.while loop structure

 The syntax of the while loop statement is as follows:

public class Hello{
	public static void main(String args[]){
		int x=5;
		String str="Hello world";
		while(x>=5)//while循环语句
		{
			System.out.println("str="+str);
			break;
		}
	}
}

4.do-while loop structure

The do-while loop structure is as follows:

public class Hello{
	public static void main(String args[]){
		int x=5;
		String str="Hello world";
		do{
			System.out.println("str="+str);
			x++;
		}while(x<=5);
	}
}

5. For loop structure

The structure of the .for loop is as follows:

public class Hello{
	public static void main(String args[]){
		int x=5;
		String str="Hello world";
		for(int i=0;i<x;i++)
		{
			System.out.println(str+(i+1));
		}
	}
}

6. Transfer statement

The Java language provides three types of unconditional transfer statements, return, break, and continue. The return is used to return the value from the method, the break statement is to jump out of the loop directly, and the continue statement is to jump out of the loop.

Guess you like

Origin blog.csdn.net/qq_25036849/article/details/108782943