zoukankan      html  css  js  c++  java
  • if 和 switch 比较

     1 package com.ibeve.demo;
     2 
     3 public class SwitchDemo {
     4     public static void main(String[] args) {
     5 
     6         int x = 4;
     7 
     8         // byte short int char
     9         switch (x) {
    10         case 4:
    11             System.out.println("a");
    12             break;
    13         case 5:
    14             System.out.println("b");
    15             break;
    16         case 6:
    17             System.out.println("c");
    18             break;
    19         default:
    20             System.out.println("d");
    21             break;
    22         }
    23 
    24         int a = 4, b = 3;
    25         char ch = '+';
    26 
    27         switch (ch) {
    28         case '+':
    29             System.out.println(a + b);
    30             break;
    31         case '-':
    32             System.out.println(a - b);
    33             break;
    34         case '*':
    35             System.out.println(a * b);
    36             break;
    37         case '/':
    38             System.out.println(a / b);
    39             break;
    40         default:
    41             System.out.println("非法数值");
    42             break;
    43         }
    44 
    45         int y = 3;
    46         switch (y) {
    47         case 3:
    48         case 4:
    49         case 5:
    50             System.out.println(y + "春季");
    51             break;
    52         case 6:
    53         case 7:
    54         case 8:
    55             System.out.println(y + "夏季");
    56             break;
    57         case 9:
    58         case 10:
    59         case 11:
    60             System.out.println(y + "秋季");
    61             break;
    62         case 12:
    63         case 13:
    64         case 14:
    65             System.out.println(y + "冬季");
    66             break;
    67         default:
    68             System.out.println("参数不合法");
    69             break;
    70         }
    71 
    72         /**
    73          * if 和 switch 语句很像
    74          * 具体什么场景下,应用哪个语句呢?
    75          * 如果判断的具体数值不多,而是符合 byte short int char 这四种类型
    76          * 虽然两个语句都可以使用,建议使用 switch 语句,因为效率稍高
    77          * 
    78          * 其他情况下,对区间判断,对结果为 boolean 类型判断,使用 if, if 的使用范围更广
    79          */
    80     }
    81 }
  • 相关阅读:
    基本运算符和if判断
    数据类型
    Day 5内存管理,定义变量
    Day 4 变量常量
    编辑语言的分类
    硬盘工作原理
    计算机组成原理
    hdu5293 lca+dp+树状数组+时间戳
    hdu5290树形dp
    hdu5294 网络流+dijskstr
  • 原文地址:https://www.cnblogs.com/believeus/p/8952611.html
Copyright © 2011-2022 走看看