选择结构
- if单选择结构
- if双选择结构
- if多选择结构
- 嵌套的if结构
- switch多选择结构
if单选择结构
-
我们很多时候需要去判断一个东西是否可行,然后我们才去执行,这样一个过程在程序中用if语句来表示。
-
语法:
if(布尔表达式){ //如果布尔表达式为true将执行的语句 }
if双选择结构
-
那现在有个需求,公司要收购一个软件,成功了,给人支付100万元,失败了,自己找人开发。这样的一个需求用一个if就搞不定了,我们需要一个双选择结构,所以就有了if-else结构。
-
语法:
if(布尔表达式){ //如果布尔表达式的值是true }else{ //如果布尔表达式的值为false }
if多选择结构
-
我们发现刚才的代码不符合实际情况,真实的情况还可能存在ABCD,存在区间多级判断。比如90-100就是A,80-90就是B…等等,在生活中我们很多时候的选择也不仅仅只有两个,所以我们需要一个多选择结构来处理这类问题!
-
语法:
if(布尔表达式1){ //如果布尔表达式1的值是true执行代码 }else if(布尔表达式2){ //如果布尔表达式2的值为true执行代码 }else if(布尔表达式3){ //如果布尔表达式3的值为true执行代码 }else{ //如果以上布尔表达式都不为true执行代码 }
嵌套的if结构
-
使用嵌套的if…else语句是合法的。也就是说你可以在另一个if或者else if语句中使用else if语句。你可以像if语句一样嵌套else if…else。
-
语句:
if(布尔表达式1){ 如果布尔表达式1的值为true执行代码 if(布尔表达式2){ 如果布尔表达式2的值为true执行代码 } }
package Struct;
import java.util.Scanner;
public class IfDemo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入内容:");
String s = scanner.nextLine();
//equals:判断字符串是否相等
if (s.equals("Hello")){
System.out.println(s);
}
System.out.println("End");
scanner.close();
}
}
package Struct;
import java.util.Scanner;
public class IfDemo02 {
public static void main(String[] args) {
//考试分数大于60就是及格,小于60就不及格
Scanner scannnr = new Scanner(System.in);
System.out.println("请输入成绩:");
int score = scannnr.nextInt();
if (score>60){
System.out.println("及格");
}else {
System.out.println("不及格");
}
scannnr.close();
}
}
package Struct;
import java.util.Scanner;
public class IfDemo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
/*
if 语句至多一个else语句,else语句在所有的else if语句之后。
if 语句可以有若干个else if 语句,他们必须在else语句之前。
一旦其中一个else if 语句检测为true,其他的else if及else语句都将跳过执行。
*/
System.out.println("请输入成绩:");
int score = scanner.nextInt();
if (score==100){
System.out.println("恭喜满分");
}else if (score<100&&score>=90){
System.out.println("A级");
}else if (score<90&&score>=80){
System.out.println("B级");
}else if (score<80&&score>=70){
System.out.println("C级");
}else if (score<70&&score>=60){
System.out.println("D级");
}else if (score<60&&score>=0){
System.out.println("不及格");
}else {
System.out.println("成绩不合法");
}
scanner.close();
}
}
switch多选择结构
- 多选择结构还有一个实现方式就是switch case语句。
- switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。
switch(expression){
case value :
//语句
break;//可选
case value :
//语句
break;//可选
//你可以有任意数量的case语句
default://可选
//语句
}
- switch 语句中的变量类型可以是:
- byte、short、int或者char。
- 从 Java SE 7 开始
- switch 支持字符串String类型了
- 同时case标签必须为字符串常量或字面量。