分支结构
if单分支
形式:
if(条件表达式){ statement… } |
if else双分支
形式:
if(条件表达式){ statement1 }else{ statement2 } |
if 多分支结构
形式:
if、else关键字只能写一次,else if视情况而定。
import java.util.Scanner; public class Test{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int score = sc.nextInt(); /* if(score >= 90){ // >= 90 System.out.println("优秀"); }else if(score <90 && score>=80){ // 80=< score < 90 System.out.println("良好"); }else if(score <80 && score >=60){ // 60=< score < 80 System.out.println("中等"); }else{ System.out.println("差"); } */ // 优化 /* if(score >= 90){ System.out.println("优秀"); }else if(score >= 80){ System.out.println("良好"); }else if(score >= 60){ System.out.println("中等"); }else{ System.out.println("差"); } */ if(score < 60){ System.out.println("差"); }else if(score < 80){ System.out.println("中等"); }else if(score < 90){ System.out.println("良好"); }else { System.out.println("优秀"); } } } |
if多分支时,如果判断大于大的值,用>,如果判断小于小的值,用<号。
if嵌套
if分支可以任意嵌套。
public class Test04{ public static void main(String[] args){ float time = 9.5f; char sex = '男'; // [1] 进入决赛 if(time < 10){ // [2]性别判断 if(sex == '男'){ System.out.println("进入男子组"); }else { System.out.println("进入女子组"); } }else{ System.out.println("oops,不能进入决赛"); } } } |
嵌套的深度不易超过4层。
多值匹配分支switch
switch (表达式) { case 值1 : 语句序列; [break]; case 值2: 语句序列; [break] ; … … … [default: 默认语句 ;] } |
// 匹配分支 switch(week){ 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; } } |
两种特殊情况
[1]省略break;
int week = 1; switch(week){ case 1:{ System.out.println("写代码"); } case 2:{ System.out.println("看电影"); } 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; } } |
[2]当多个case的结果一行时,可以省略整个语句块
public class Test08{ public static void main(String[] args){ // 随机产生一个字符(a-z)判断是元音还是辅音 // [a,z] // [0,25]+a int r = (int)(Math.random() * (25-0+1)) + 0; char c = (char)(r + 'a'); System.out.println("c = " + c); switch(c){ case 'a': case 'e': case 'i': case 'o': case 'u':{ System.out.println("元音:"+c); break; } case 'y': case 'r': case 'w':{ System.out.println("半元音:"+c); break; } default:{ System.out.println("辅音:"+c); break; } } } } |
switch表达式支持的匹配方式有整形、char、字符串(jdk1.7以上),迫不得已时不要用字符串匹配,字符串在switch匹配过程中,效率极低。
if条件分支和switch等值分支比较
相同点:都是分支语句。
不同点:switch 只能进行等值匹配,且条件必须是整形、char类型,jdk1.7之后支持字符串。
if 没有switch选择结构的限制,特别适合某个变量处于某个连续区间时的情况。