选择结构
1、if选择结构(单条件)
if(45<56){
}
2、if -else选择结构(if-else结构构成了全集)
if(5>2){
}else{
}
3、多重if
if(i>90 && i<100){
System.out.println("i在90到100之间");
}else if(i>80 && i<90){
System.out.println("i在80到90之间");
}else if(i>70 && i<80){
System.out.println("i在70到80之间");
}else{
System.out.println("i不在70到100之间");
}
注意:
1)最后else可省,根据具体的业务
2)else和if是分开,中间有空格
3)else if可以存在多个
4)适用于连续的区间判断,顺序不能颠倒
4、嵌套if
if(time <=10){
System.out.println("恭喜你进入居然赛,请输入性别,给您分组(male,female)");
String gender = sc.next();
if("male".equals(gender)){
System.out.println("您被分配到男子组");
} else if ("female".equals(gender)) {
System.out.println("您被分配到女子组");
} else {
System.out.println("您输入的性别有误");
}
}else {
System.out.println("您的比赛成绩到此结束");
}
5、switch选择结构
语法:
switch (表达式) {
case 常量1:
语句;
break;
case 常量2:
语句;
break;
…
default:
语句;
}
注意:
1)表达式支持的基本类型:int,byte,short,char,特殊类型:枚举类型,String类型
2)每个case匹配执行结束,要加break关键字,分号结尾,作用是结束分支结构
3)case后面的常量值,不能重复
4)default的顺序,没有固定要求,但是一般建议写在最后,且加上break;关键字,也可以省略不写
6、switch和多重if的异同
相同点:
都是用于处理多分支条件判断
不同点:
switch:只能处理等值的条件判断
多重if:没有switch的条件限制,一般用于连续的区间条件判断(某个值在固定的区间范围内)