7.1 顺序结构
//顺序结构
public class Demo01Sequence{
public static void main(String[] args){
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");//1、2、3、4都能输出
}
}
7.2 单If语句
//单if语句
public class Demo02If{
public static void main(String[] args){
System.out.println("网吧");
int age = 17;//输出的是 网吧 回家
//int age = 19;//五条语句都能输出
if (age >= 18){
System.out.println("进入网吧");
System.out.println("打游戏");
System.out.println("结账");
}
System.out.println("回家");
}
}
7.3 if-else语句
//标准的if-else语句
public class Demo03IfElse{
public static void main(String[] args){
int num = 66;
if (num % 2 == 0){//如果除以2能够余数为0,说明是偶数
System.out.println("偶数");
}else{
System.out.println("奇数");
}
}
}
7.4 扩展if-else语句
//x和y的关系满足如下:
//如果x >= 3,那么y = 2x +1;
//如果-1 < x < 3,那么y = 2x;
//如果x <= -1,那么y = 2x - 1;
public class Demo04IfElse{
public static void main(String[] args){
int x = -10;
int y;
if (x >=3){
y = 2 * x + 1;
} else if (-1 < x && x < 3){
y = 2 * x;
}else{
y = 2 * x -1;
}
System.out.println("结果是:" + y);
}
}
7.5 用If-else语句实现考试成绩划分
public class Demo05Practise{
public static void main(String[] args){
int score = 80;
if (score >=90 && score <= 100){
System.out.println("优秀");
}else if (score >=80 && score < 90){
System.out.println("好");
} else if (score >=70 && score < 80){
System.out.println("良");
} else if (score >=60 && score < 70){
System.out.println("及格");
} else if (score >=0 && score < 60){
System.out.println("不及格");
} else {//单独处理边界之外的不合理情况
System.out.println("数据错误");
}
}
}
7.6 用if-else语句替换三元运算符
//使用三元运算符和标准的if-else语句分别实现:取两个数字当中的最大值
public class Demo06Max{
public static void main(String[] args){
int a = 10;
int b = 20;
//首先使用三元运算符
//int max = a > b ? a : b;
//使用今天的if语句
int max;
if (a > b){
max = a;
}else{
max = b;
}
System.out.println("最大值:" + max);
}
}
7.7 switch语句
public class Demo07Switch{
public static void main(String[] args){
int num = 4;
switch (num){
case 1:
System.out.println("星期一");
break;
case 2:
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语句可以省略,但是强烈推荐不要省略
}
}
}
7.8 穿透的switch语句
/*
switch语句使用的注意事项:
1.多个case后面的数值不可以重复;
2.switch后面的小括号当中只能是下列数据类型:
基本数据类型:byte/short/char/int
引用数据类型:String字符串、enum枚举
3.switch语句格式可以很灵活:前后顺序可以颠倒,而且break语句还可以省略。
”匹配哪一个case就从哪一个位置向下执行,直到遇到了break或者整体结束为止。“
*/
public class Demo08SwitchNotice{
public static void main(String[] args){
int num = 2;
switch (num) {
case 1:
System.out.println("A");
break;
case 2:
System.out.println("B");
//break;
case 3:
System.out.println("C");
break;
default:
System.out.println("D");
break;
}//输出B和C,因为case2中没有写break,穿透case3向下执行,直到遇到break
}
}