流程控制语句
流程指程序执行的先后顺序
1. 顺序结构
public static void main(String[] args)
{
System.out.println(1);
System.out.println(2);
System.out.println(3);
}
2. 判断 if语句
if(关系表达式最终得到布尔值即可) {
语句体;
}
public static void main(String[] args)
{
System.out.println("去网吧");
int age = 16;
if(age >= 18){
System.out.println("可以进入"); //判断语句,满足则执行,不满足直接跳到最后
}
System.out.println("未满18周岁离开");
}
3. if-else 语句
if(关系表达式最终得到布尔值即可) {
语句体1;
}else{
语句体2;
}
适用于2选1的情况
public static void main(String[] args) 实例判断基偶
{
int num = 13;
if(num % 2 == 0){ //使用取模能除尽为偶数,否则为基数
System.out.println("偶数");
}else{
System.out.println("基数");
}
4. if-else 复合语句
if(判断条件1) {
执行语句体1;
}else if (判断条件2){
执行语句体2;
}
…
}else if (判断条件n ) {
执行语句n;
}else{
执行语句n+1;
}
适用于多选1的情况
public static void main(String[] args) 实例判断基偶
{
int x = 13;
int y = ;
if (x >= 3){ //假设x为4 条件成立,
y = 2 * x + 1; //结果为 9
} else if (-1 < x && x < 3){ //假设x为2 条件成立,
y = 2 *x; //结果为 4
}else{ //假设x为-1与上述条件均不成立,直接跳转最后一步
y = 2 * x - 1; //结果为 -3
}
System.out.println("结果是" + y);
}
练习
public static void main(String[] args)
int score = 98;
if(score >= 90 && <=100){ //90<变量<100
System.out.println("优秀");
}else if (score >= 80 && <=90){ //80<变量<90
System.out.println("好");
}else if (score >= 70 && <=80){ //70<变量<80
System.out.println("良");
}else if (score >= 0 && <=70){ //0<变量<70
System.out.println("不及格");
}else{
System.out.println("数据错"); //超出条件判断外的数字为不合理
}
5. Switch 语句
代码格式:
switch(表达式){
case 常量值1:
语句体;
break;
case 常量值2:
语句体2;
break;
...
default:
语句体n+1;
break;
}
案例:
满足匹配哪个case 就向下执行
public static void main(String[] args)
int num = 1;
switch (num){
case 1; //case 后为常量
System.out.println("星期一");
break;
case 2;
System.out.println("星期二");
break;
case 3;
System.out.println("星期三");
break;
default: //类似于else
System.out.println("数据错"); //超出条件判断外的数字为不合理
break;
}
tips: case 后数值不可相同