Java Switch语句 - “或”/“和”可能吗?

时间:2012-03-27 03:44:50

标签: java char switch-statement

我实现了一个字体系统,通过char switch语句找出要使用的字母。我的字体图片中只有大写字母。我需要这样做,例如,'a'和'A'都有相同的输出。而不是2倍的案件数量,它可能是如下:

char c;

switch(c){
case 'a' & 'A': /*get the 'A' image*/; break;
case 'b' & 'B': /*get the 'B' image*/; break;
...
case 'z' & 'Z': /*get the 'Z' image*/; break;
}

这在java中是否可行?

5 个答案:

答案 0 :(得分:172)

您可以通过省略break;语句来使用switch-case。

char c = /* whatever */;

switch(c) {
    case 'a':
    case 'A':
        //get the 'A' image;
        break;
    case 'b':
    case 'B':
        //get the 'B' image;
        break;
    // (...)
    case 'z':
    case 'Z':
        //get the 'Z' image;
        break;
}

...或者您可以在switch之前标准化为lower caseupper case

char c = Character.toUpperCase(/* whatever */);

switch(c) {
    case 'A':
        //get the 'A' image;
        break;
    case 'B':
        //get the 'B' image;
        break;
    // (...)
    case 'Z':
        //get the 'Z' image;
        break;
}

答案 1 :(得分:18)

上面,你的意思是OR而不是AND。 AND的例子:110& 011 == 010这不是你想要的东西。

对于OR,只有2例没有中断的情况。例如:

case 'a':
case 'A':
  // do stuff
  break;

答案 2 :(得分:7)

以上都是很好的答案。我只是想补充一点,当有多个字符需要检查时,if-else可能会变得更好,因为您可以改为编写以下内容。

// switch on vowels, digits, punctuation, or consonants
char c; // assign some character to 'c'
if ("aeiouAEIOU".indexOf(c) != -1) {
  // handle vowel case
} else if ("!@#$%,.".indexOf(c) != -1) {
  // handle punctuation case
} else if ("0123456789".indexOf(c) != -1) {
  // handle digit case
} else {
  // handle consonant case, assuming other characters are not possible
}

当然,如果这变得更复杂,我建议使用正则表达式匹配器。

答案 3 :(得分:1)

根据我对您的问题的理解,在将字符传递给switch语句之前,您可以将其转换为小写。因此,您不必担心大写,因为它们会自动转换为小写。 为此,您需要使用以下功能:

Character.toLowerCase(c);

答案 4 :(得分:1)

对有趣Switch case陷阱的观察 - > fall through

switch

“中断语句是必要的,因为如果没有它们,交换机块中的语句就会失败:” Java Doc's example

连续case没有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是:

A

但是如果你改变c的值,即char c = 'a';,那么这就变得有趣了。

这种情况的O / P是:

a A

即使第二个案例测试失败,程序也会进入打印A,因为缺少break会导致switch将其余代码视为一个块。匹配的案例标签之后的所有语句都按顺序执行。