if single choice structure
-
grammar:
if(Boolean expression){
//If the Boolean expression is true, the statement will be executed
}
-
Process:
-
Example:
Scanner scanner = new Scanner(System.in); System.out.println("请输入内容"); String s = scanner.nextLine(); //equais:比较字符串是否相等 if (s.equals("这是if单选择结构")){ System.out.println(s); } System.out.println("经条件判断不相等,End"); scanner.close();
if double selection structure
-
grammar:
if(Boolean expression){
//If the Boolean expression is true, the statement will be executed
}else{
//The statement that will be executed if the boolean expression is false
}
-
Process:
-
Example:
The company wants to acquire a piece of software. If it succeeds, it pays one million. If it fails, it finds someone to develop it.
Scanner scanner = new Scanner(System.in); System.out.println("公司收购软件成功了吗:"); String s = scanner.nextLine(); if (s.equals("成功")){ System.out.println("支付一百万"); }else { System.out.println("自己找人开发"); }
if multiple choice structure
-
grammar:
if(Boolean expression 1) {
//If the Boolean expression 1 is true, the statement will be executed
}else if(Boolean expression 2){
//If the Boolean expression 2 is true, the statement will be executed
}else if(Boolean expression 3){
//If the Boolean expression 2 is true, the statement will be executed
}else{
//If all the above Boolean expressions are not true, the statement will be executed
}
-
Process:
-
Example:
Scanner scanner = new Scanner(System.in); System.out.println("请输入成绩:"); double score = scanner.nextDouble(); if (score == 100){ System.out.println("满分"); }else if (score >=90 && score < 100){ System.out.println("A"); }else if (score >=80 && score < 90){ System.out.println("B"); }else if (score >=60 && score < 80){ System.out.println("C"); }else if (score < 60){ System.out.println("不及格"); }else{ System.out.println("成绩不合法"); } scanner.close();
-
Note on if multiple selection structure
The if statement has at most one else statement, the else statement is after all else if statements;
The if statement can have several else if statements, they must be before the else statement;
Once one of the else if statements is detected as true, the other else if statements and else statements will be skipped;
Both the if statement and the else if statement have Boolean expressions in parentheses, only the else statement does not.
Nested if structure
- It is legal to use nested if...else statements.
- if(Boolean expression 1) {
//If the Boolean expression 1 is true, the statement will be executed
if(Boolean expression 2) {
//The statement that will be executed if the Boolean expression 2 is true
}
}