Java–分支结构
if(条件表达式){
执行代码块;
}
else if(条件表达式){
执行代码块;
}
……
else{
执行代码块;
}
- 例题:判断小明的考试成绩,如果分数是100,则奖励一辆BMW;如果分数在(80,99]之间,奖励一个iphone5s;如果分数在[60,80]之间,奖励一本参考书;若果分数小于60,则什么奖励也没有。
public class w {
public static void main(String[]args) {
int i=100;
if(i==100) {
System.out.println("BMW");
}
else if (i>80&&i<=99) {
System.out.println("iphone5s");
}
else if(i>60&&i<=80) {
System.out.println("参考书");
}
else {
System.out.println("什么也没有");
}
}
}
switch(常量){
case 常量1:
语句1;
break;
case 常量2:
语句2;
break;
.......
default:
语句;
break;
}
- 例子:使用switch把小写类型的char型转为大写。只转换a,b,c,d,其他输出为other。
public class w {
public static void main(String[]args) {
char c='f';
switch (c) {
case 'a':
System.out.println("A");
break;
case 'b':
System.out.println("B");
break;
case 'c':
System.out.println("C");
break;
case 'd':
System.out.println("D");
break;
default:
System.out.println("other");
break;
}
}
}
- 注意:
- switch(表达式)中表达式的返回值必须是以下几种类型之一:byte,short,char,int,string
- case子句中的值必须是常量,且所有的case子句中的值都是不同的
- default子句是任选的,当没有匹配的case时,执行default
- break语句用来执行完一个case分支后,使程序跳出switch语句块,如果没有break,程序会按顺序执行到switch结尾。break是必须写的,不然case匹配到位置开始一直执行到结尾。
- if-else和switch的使用
- 如果判断的具体数值不多,而且符合byte,short,int,char这四种类型,虽然两个语句都可以使用,建议使用switch语句,效率较高。
- 其他:对区间判断,对结果为Boolean类型判断,使用if-else语句,范围更广。