`
fanyo
  • 浏览: 43684 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类
最新评论

Switch 没有break和default位置乱放情况分析

阅读更多
package flowcontrol;

public class SwitchCase {
	// first default
	public static void testFirst(int i) {
		switch (i) {
		default:
			System.out.println("default");// first default
		case 1:
			System.out.println("one");
		case 2:
			System.out.println("two");
		case 3:
			System.out.println("there");
		}
	}

	// last default
	public static void testLast(int i) {
		switch (i) {
		case 1:
			System.out.println("one");
		case 2:
			System.out.println("two");
		case 3:
			System.out.println("there");
		default:
			System.out.println("default");// last default
		}
	}

	// middle default
	public static void testMiddle(int i) {
		switch (i) {
		case 1:
			System.out.println("one");
		case 2:
			System.out.println("two");
		default:
			System.out.println("default");// middle default
		case 3:
			System.out.println("there");

		}
	}

	public static void main(String[] args) {
		// first default
		testFirst(2);
		System.out.println("------------------");
		testFirst(9);

		System.out.println("|||||||||||||||||||||||||||||||||||");

		// last default
		testLast(2);
		System.out.println("----------------");
		testLast(9);

		System.out.println("|||||||||||||||||||||||||||||||||||");
		// middle default
		testMiddle(2);
		System.out.println("----------------");
		testMiddle(9);

	}

}



输出结果是什么呢,看了结果,我是这么理解的:
(1)switch语句关键地方是进入点,有了进入点没有break的情况下会执行到底
(2)没有匹配值的时候default就是进入点,进入default以后会和普通进入点一样,如果没有break继续执行下面语句
two
there
------------------
default
one
two
there
|||||||||||||||||||||||||||||||||||
two
there
default
----------------
default
|||||||||||||||||||||||||||||||||||
two
default
there
----------------
default
there
分享到:
评论
1 楼 fanyo 2009-08-10  
public class B {  
       
    public static void main(String Args[]){  
        int i =1 ,j =0;  
          
        switch(i){  
            default:j+=2;  
            case 2:j+=6;  
            case 4:j+=6;  
              
            case 0:j+=4;  
              
              
        }  
          
      
          
        System.out.println(j);  
          
    }  

这样就不难理解输出结果18了
switch 每次搞懂了记住了,然后又混了,特别default 和break 组合很乱的时候,
记住进入点,和 没break 顺序进行,感觉思路清晰多了

相关推荐

Global site tag (gtag.js) - Google Analytics