Java语言基础------分支流程控制

一时失言乱红尘 2022-03-15 12:16 330阅读 0赞

分支流程控制

if 单路分支

  1. if的原理案例:
  2. 案例代码:

    1. public static void main(String[] args) {
    2. /** * if 流程控制 */
    3. int i = 5;
    4. Scanner console = new Scanner(System.in);
    5. System.out.print("输入总价:");
    6. double total = console.nextDouble();
    7. if(total>=200) {
    8. total *= 0.9;
    9. }
    10. System.out.println("应付款:"+total);
    11. }

if else

  1. if else原理案例:
  2. 案例代码:

    1. public static void main(String[] args) {
    2. /** * if ... else 分支流程控制 */
    3. @SuppressWarnings("resource")
    4. Scanner console = new Scanner(System.in);
    5. System.out.print("输入总价:");
    6. double total = console.nextDouble();
    7. if(total>=200) {
    8. total *= 0.8;
    9. } else {
    10. total *= 0.95;
    11. }
    12. System.out.println("应付:"+total);
    13. }

if/eles if/else 多路分支

  1. if/eles if/else原理案例:
  2. 案例代码:

    1. public static void main(String[] args) {
    2. /** * if else if 多路分支流程控制 */
    3. Scanner console = new Scanner(System.in);
    4. System.out.print("输入总价:");
    5. double total = console.nextDouble();
    6. //if语句块中只有一行代码时候,可以省略{ }
    7. if(total<200)
    8. total *= 0.95;
    9. else if(total<500)
    10. total *= 0.8;
    11. else if(total<800)
    12. total *= 0.5;
    13. else
    14. total *= 0.3;
    15. System.out.println("应付:"+total);
    16. }

switch case

  1. switch case原理:
  2. 案例:
  3. 代码:

    1. public static void main(String[] args) {
    2. /** * switch case 分支演示 */
    3. Scanner console = new Scanner(System.in);
    4. System.out.print("输入百分制分数:");
    5. int score = console.nextInt();
    6. switch(score/10) {
    7. case 10://不加break,可以复用 case 块!
    8. case 9:
    9. System.out.println("A"); break;
    10. case 8:
    11. System.out.println("B"); break;
    12. case 7:
    13. case 6:
    14. System.out.println("C"); break;
    15. default:
    16. System.out.println("D");
    17. }
    18. }

多路分支的选择问题

  1. switch case

    1. 根据整数(byte,short,char,int)进行分支
    2. 只计算一次整数表达式,根据整数直接跳转,性能好
    3. Java 5 扩展了枚举类型分支,枚举常量
    4. Java 7 扩展了字符串分支,字符串常量
  2. if else if

    1. 根据任意条件进行分支,适用范围广阔
    2. 需要多次执行分支条件,没有switch case性能好

发表评论

表情:
评论列表 (有 0 条评论,330人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java基础流程控制

    上次的运算符都消化好了吗?每一天都要用到一些哦~ 以前有提到过一嘴,程序执行都是从上到下执行的,emm,学到这里,感觉这句话是对的也是错的了…… 如果都是一行一行执行下去的