版权声明:欢迎转载 https://blog.csdn.net/qq_37875585/article/details/88077591
分支流程控制
if 单路分支
- if的原理案例:
- 案例代码:
public static void main(String[] args) { /** * if 流程控制 */ int i = 5; Scanner console = new Scanner(System.in); System.out.print("输入总价:"); double total = console.nextDouble(); if(total>=200) { total *= 0.9; } System.out.println("应付款:"+total); }
if else
- if else原理案例:
- 案例代码:
public static void main(String[] args) { /** * if ... else 分支流程控制 */ @SuppressWarnings("resource") Scanner console = new Scanner(System.in); System.out.print("输入总价:"); double total = console.nextDouble(); if(total>=200) { total *= 0.8; } else { total *= 0.95; } System.out.println("应付:"+total); }
if/eles if/else 多路分支
- if/eles if/else原理案例:
- 案例代码:
public static void main(String[] args) { /** * if else if 多路分支流程控制 */ Scanner console = new Scanner(System.in); System.out.print("输入总价:"); double total = console.nextDouble(); //if语句块中只有一行代码时候,可以省略{ } if(total<200) total *= 0.95; else if(total<500) total *= 0.8; else if(total<800) total *= 0.5; else total *= 0.3; System.out.println("应付:"+total); }
switch case
- switch case原理:
- 案例:
- 代码:
public static void main(String[] args) { /** * switch case 分支演示 */ Scanner console = new Scanner(System.in); System.out.print("输入百分制分数:"); int score = console.nextInt(); switch(score/10) { case 10://不加break,可以复用 case 块! case 9: System.out.println("A"); break; case 8: System.out.println("B"); break; case 7: case 6: System.out.println("C"); break; default: System.out.println("D"); } }
多路分支的选择问题
- switch case
- 根据整数(byte,short,char,int)进行分支
- 只计算一次整数表达式,根据整数直接跳转,性能好
- Java 5 扩展了枚举类型分支,枚举常量
- Java 7 扩展了字符串分支,字符串常量
- if else if
- 根据任意条件进行分支,适用范围广阔
- 需要多次执行分支条件,没有switch case性能好