Java Switch Statement - Is “or”/“and” possible?

前端 未结 5 1805
说谎
说谎 2020-12-14 05:24

I implemented a font system that finds out which letter to use via char switch statements. There are only capital letters in my font image. I need to make it so that, for ex

5条回答
  •  盖世英雄少女心
    2020-12-14 06:03

    Observations on an interesting Switch case trap --> fall through of switch

    "The break statements are necessary because without them, statements in switch blocks fall through:" Java Doc's example

    Snippet of consecutive case without break:

        char c = 'A';/* switch with lower case */;
        switch(c) {
            case 'a':
                System.out.println("a");
            case 'A':
                System.out.println("A");
                break;
        }
    

    O/P for this case is:

    A

    But if you change value of c, i.e., char c = 'a';, then this get interesting.

    O/P for this case is:

    a A

    Even though the 2nd case test fails, program goes onto print A, due to missing break which causes switch to treat the rest of the code as a block. All statements after the matching case label are executed in sequence.

提交回复
热议问题