日期:2014-05-20  浏览次数:20654 次

这段程序的结果为什么是这样?关于switch
首先声明这段程序是一道读程序写结果的题目,我本人知道第一分支少一个break,只是对输出结果是   Value   is   two.
                              Value   is   three.
而不是   Value   is   two.
              Value   is   2     感到奇怪!!!!

public   class   SwitchTest
{
    public   static   void   main(String[]   args)
    {
        int   j   =   2;
        switch   (   j   )
        {
            case   2:
                System.out.println( "Value   is   two. ");
            case   10:
                System.out.println( "Value   is   three. ");
                break;
            default:
                System.out.println( "Value   is   "   +   j);
                break;
        }
    }
}


------解决方案--------------------
程序是顺序执行的,
case 2:
System.out.println( "Value is two. ");
//这个之后没有break,就会顺序执行以下语句:
case 10:
System.out.println( "Value is three. ");
break;
//遇到break后跳出switch,也就不会执行default的内容了