switch..case函数的基础使用一

基本作用:switch中的参数与case的值进行比对,相等则进入case。

JDK1.7 switch支持int、Integer、String类型

package com.my.test;

import junit.framework.TestCase;

public class commonTest extends TestCase{
    /**
     * switch
     * switch中的参数与case的值进行比对,相等则进入case。
     */
    public void test(){
        int[] a = new int[4];
        a[0] = 1;a[1] = 2;a[2] = 3;a[3] = 4;
        for (int i = 0; i < a.length; i++) {
            switch (a[i]) {//参数为int类型
                case 1:
                    System.out.println(a[i]);
                    break;
                case 2:
                    System.out.println(a[i]);
                    break;    
                default:
                    System.out.println("default:"+a[i]);
                    break;
            }
        }
     }
    public void test2(){
        int[] a = new int[4];
        a[0] = 1;a[1] = 2;a[2] = 3;a[3] = 4;
        for (int i = 0; i < a.length; i++) {
            switch (Integer.parseInt(a[i]+"")) {//参数为Integer类型
                case 1:
                    System.out.println(a[i]);
                    break;
                case 2:
                    System.out.println(a[i]);
                    break;    
                default:
                    System.out.println("default:"+a[i]);
                    break;
            }
        }
     }
    public void test3(){
        String[] a = new String[4];
        a[0] = "a";a[1] = "b";a[2] = "c";a[3] = "d";
        for (int i = 0; i < a.length; i++) {
            switch (a[i]) {//参数为String类型
                case "a":
                    System.out.println(a[i]);
                    break;
                case "b":
                    System.out.println(a[i]);
                    break;    
                default:
                    System.out.println("default:"+a[i]);
                    break;
            }
        }
     }
    

}

结果:

test:

1
2
default:3
default:4

test2:

1
2
default:3
default:4

test3:

a
b
default:c
default:d

原文地址:https://www.cnblogs.com/wql025/p/5229082.html