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

Gla*_*Zee 71 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;
}
Run Code Online (Sandbox Code Playgroud)

这在Java中可行吗?

Mat*_*all 182

您可以通过省略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;
}
Run Code Online (Sandbox Code Playgroud)

...或者你可以在进入之前将小写大写归一化switch.

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上,在非常偶然的情况下需要保留`c`的情况,我会将`toUpperCase`放在开关内.但是+1因为这样可以节省很多不必要的`case`语句:-) (10认同)
  • 没问题,Charizard. (3认同)

Din*_*nah 18

以上,你的意思是OR而不是AND.AND的例子:110&011 == 010这不是你要找的东西.

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

case 'a':
case 'A':
  // do stuff
  break;
Run Code Online (Sandbox Code Playgroud)

  • 我不知道第一位对OP有多大帮助. (6认同)
  • @MДДББДLL:关于 AND 的评论表明了为什么 OP 想要 OR 而不是 AND。OR 部分与接受的答案相同,所以我希望它是相关的。 (2认同)

sco*_*awg 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
}
Run Code Online (Sandbox Code Playgroud)

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

  • `== 0`不正确.那就是说"是`c`是字符串的第一个字符?",你可能想要`> = 0`或`!= -1`. (3认同)