选择结构
if语句
用if语句根据考试成绩判断成绩等级
public class If {
public static void main (String [] args){
int score = 60;
if (score >= 85 && score <= 100){
System.out.println("你的成绩属于优秀");}
else if (score >= 70 && score <85){
System.out.println("你的成绩属于良好");
}
else if (score >= 60 && score <70){
System.out.println("你的成绩属于一般");
}
else if (score <60 && score >= 0) {
System.out.println("你的成绩属于不及格");
}
else {
System.out.println("你的成绩是错误的");
}
}
}
用if语句替代三元运算符
题目:用三元运算符和if语句分别实现:求两个数中的最大值。
//三元运算符
public class If {
public static void main(String[] args) {
int a = 10;
int b = 20;
int max = a>b ? a:b;
System.out.println("最大值是:"+max);
}
}
//if语句
public class If {
public static void main(String[] args) {
int a = 10;
int b = 20;
if (a>b) {
System.out.println("最大值是:"+a);
}
else {
System.out.println("最大值是:"+b);
}
}
}
switch语句
注意事项:
- 多个case后面的数值不可以重复
- switch后面的小括号只能是下列数据类型:
- 基本数据类型:byte/short/char/int
- 引用数据类型 String字符串、enum枚举
- switch语句格式可以很灵活:前后顺序可以颠倒,break可以省略
switch语句的穿透性
匹配到哪个case就从哪一个位置向下执行,直到遇到了break或者整体结束为止。
//最终输出结果: 大家好
public class Switch {
public static void main (String [] args){
int num = 5;
switch (num){
case 1:
System.out.println("你好");
break;
case 2:
System.out.println("我好");
break;
case 3:
System.out.println("他好");
break;
default:
System.out.println("大家好");
}
}
}