Java Switch Statement

后端 未结 8 2225
南笙
南笙 2021-02-07 13:48

I have a problem using switch statement when I tried to deal with a special situation. For example, I have 3 cases: A, B, C.

  • for A, I want to do statement_1 and st
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 14:16

    i would recommend to define exactly what staments should be executed:

    switch (variable){
        case A: 
            statement_1();
            statement_3();
            break;
        case B: 
            statement_2();
            statement_3();
            break;
    }
    

    for Update-3:

    create methods for those 10 lines:

    public void statement_1() {
        //your 10 lines of code
    }
    

    if you're always executing statement_3, except for case C you can go with if/else-blocks as you wrote them.

    but in my honest opinion: define EXACTLY what has to be done in which case if you have a small amount of cases. it is easier to read for others

提交回复
热议问题