一、顺序结构
顺序结构就是指程序从上到下顺序执行。
二、选择结构之if语句
下面是if…else语句
/*
指定考试成绩,判断成绩的等级:
90-100 优秀
80-89 好
70-79 良
60-69 及格
60 以下不及格
*/
public class Demo01If {
public static void main(String[] args) {
int score=99;
if (score<0 ||score>100){
System.out.println("你的成绩是错误的");
}else if (score>=90 && score<=100){
System.out.println("你的成绩属于:优秀");
}else if (score>=80 && score<=89){
System.out.println("你的成绩属于:好");
}else if (score>=70 && score<=79){
System.out.println("你的成绩属于:良");
}else if(score>=60 && score<=69){
System.out.println("你的成绩属于:及格");
}else {
System.out.println("你的成绩属于:不及格");
}
}
}
用if替代三元运算符
public static void main(String[] args) {
int a=30;
int b=40;
int max;
//这里可以用三元运算符
//max = a>b?a:b;
//用if语句
if (a>=b){
max=a;
}else{
max=b;
}
System.out.println("最大值是:"+max);
}
三、选择结构之switch语句
/*switch语句的格式为:
switch(表达式){
case 常量值1:
语句体1;
break;
case 常量值2:
语句体2;
break;
...
defult:
语句体n;
break;
}
*/
public class Demo01If {
public static void main(String[] args) {
int num=1;
switch (num) {
case 1:
System.out.println("星期一");
break;
case 3:
System.out.println("星期二");
break;
case 4:
System.out.println("星期二");
break;
case 5:
System.out.println("星期二");
break;
case 6:
System.out.println("星期二");
break;
case 7:
System.out.println("星期二");
break;
default:
System.out.println("数据错误");
break; //最后这一个break可以不写,但是强烈建议不省略
}
}
}
switch语句使用注意事项:
1、多个case后面的数值不可以重复。
2、switch后面的小括号当中只能是以下数据类型:
基本数据类型:byte/short/int/char
引用类型:String字符串、enum枚举
3、switch语句格式很灵活,前后顺序可以颠倒,而且break还可以省略。
“匹配哪一个case就从哪一个位置执行下去,直到遇到了break或者整体语句结束为止”。