Switch Statements

左心房为你撑大大i 提交于 2019-12-01 18:32:03

问题


For switch statements, is it possible to change the value of the switch inside the switch statement so that it can jump around to different cases? Ex:

int w = 0;
switch(w)
{
   case 1:
     doSomething();
     w = 3;
   case 2:
     doSomething();
     break;
   case 3:
     doSomething();
     break;
}

Basically what I'm asking is, if I do not place a break statement for a case and I change the value of the switch in the same case, will the code execute both cases?


回答1:


Yes you can change the value inside switch but it will not execute case for new value until you break in the case where you changed the value.

In your case it will not go in any case as there is no case for 0. But if you change to w = 1 then it will go for case 1 and then for case 2 as you do not have break; but it will not go for case 3.




回答2:


No, it will not change and will not execute new case statement.

Remember that, once appropriate match is found with the case statement corresponding to a value inside the switch statement, that particular case is executed and once that is executed ( if break is provided after each case to prevent falling through all cases) , then the control returns to the end of switch statement.

Sample Code :

public  class A {
            public static void main(String [] args) {
                    int i=1;
                    switch(i) {
                            case 1 : 
                                    System.out.println("Case 1");
                                    i = 2;
                                    break;
                            case 2 : 
                                    System.out.println("Changed to Case 2");
                                    break;

                             default:
                                    System.out.println("Default");
                                    break;
                            }

                    System.out.println("Final value of i " + i);
            }
    }

Output :

Case 1
Final value of i 2  

Note : Inserting proper breakpoints, try to debug. You will come to know yourself, what exactly is happening.




回答3:


If we do not give break after each case then Java will start executing the statement from matching case and keep on executing statements for following cases as well, until either a break statement is found or switch statements end is encountered.




回答4:


If case 1 happens to execute, it's just a fall through to the case 2. And since there is a break in case 2, further fall through doesn't happen. It doesn't jump to case 3 because of the statement w = 3 ; in case 1.



来源:https://stackoverflow.com/questions/6105740/switch-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!