Unable to get behaviour of Switch case in java

后端 未结 8 900
迷失自我
迷失自我 2021-01-23 14:07

I have written small code in java 6

public class TestSwitch{

public static void main(String... args){
    int a = 1;
    System.out.println("start");
          


        
8条回答
  •  Happy的楠姐
    2021-01-23 14:27

    switch(a){
        case 1:{
            System.out.println(1);
            case 3:
    

    You cannot nest cases like this. Switch should look either like :

        switch(a){
        case 1:
            System.out.println(1);
            break;
        case 3:
           ....
    

    or like this :

    switch(a){
        case 1:
            System.out.println(1);
            switch(a) {
                case 3:
                    //...
                    break;
                case 5 :
                    //...
    

    And if you don't add break at the end of a case, the execution will continue after. You should add a break at the end of each cases if they should be executed separately.

提交回复
热议问题