Java学习笔记_02 条件语句
条件语句
if...else 语句
if(布尔表达式){ //true, 执行代码_1 代码_1
.....
}else{ //false, 执行代码_2
代码_2
.....
}
if...else if...else 语句
if(布尔表达式_1){ //如果布尔表达式 1的值为true执行代码 }else if(布尔表达式_2){ //如果布尔表达式_2的值为true执行代码 }else if(布尔表达式_3){ //如果布尔表达式_3的值为true执行代码 }else { //以上的结果都不符合,布尔值为false }
嵌套if 语句
if 语句可嵌套使用
if(布尔表达式_1){ ////如果布尔表达式 1的值为true执行代码 if(布尔表达式_2){ ////如果布尔表达式 2的值为true执行代码 } }
public class Stu_4_1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入你的成绩:"); int sum = sc.nextInt(); if (sum > 100 || sum < 0) { System.out.println("告诉我,你的真实成绩"); } else if (sum > 95 && sum <= 100) { System.out.println("一辆自行车"); } else if (sum > 90 && sum <= 95) { System.out.println("去游乐园"); } else if (sum >= 80 && sum <= 90) { System.out.println("一个玩具"); } else { System.out.println("补习班"); } } }
switch 语句
判断一个变量与一系列值中某个值是否相等,每个值称为一个分支
switch(expression){ case value : //执行的代码 .... break; //可选 case value : //执行的代码 .... break; //可选 ......... default : //可选
//默认选择, 以上case不符合,则会执行default //执行的代码 .... break; }
switch case 语句有如下规则:
-
switch 语句中的变量类型可以是: byte、short、int 或者 char。从 Java SE 7 开始,switch 支持字符串 String 类型了,同时 case 标签必须为字符串常量或字面量。
-
switch 语句可以拥有多个 case 语句。每个 case 后面跟一个要比较的值和冒号。
-
case 语句中的值的数据类型必须与变量的数据类型相同,而且只能是常量或者字面常量。
-
当变量的值与 case 语句的值相等时,那么 case 语句之后的语句开始执行,直到 break 语句出现才会跳出 switch 语句。
-
当遇到 break 语句时,switch 语句终止。程序跳转到 switch 语句后面的语句执行。case 语句不必须要包含 break 语句。如果没有 break 语句出现,程序会继续执行下一条 case 语句,直到出现 break 语句 (case穿透)。
-
switch 语句可以包含一个 default 分支,该分支一般是 switch 语句的最后一个分支(可以在任何位置,但建议在最后一个)。default 在没有 case 语句的值和变量值相等的时候执行。default 分支不需要 break 语句。
switch case 执行时,一定会先进行匹配,匹配成功返回当前 case 的值,再根据是否有 break,判断是否继续输出,或是跳出判断。
public class Stu_4_2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入月份:"); int i = sc.nextInt(); // 使用case穿透 switch (i){ case 1: case 2: case 12: System.out.println("冬天"); break; case 3: case 4: case 5: System.out.println("春天"); break; case 6: case 7: case 8: System.out.println("夏天"); break; case 9: case 10: case 11: System.out.println("秋天"); break; default: System.out.println("你输入的月份有误"); break; } } }

浙公网安备 33010602011771号