Java交换语句 – 是“或”/“和”可能吗?

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

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中可能吗?

你可以通过忽略break;来使用switch-case break; 声明。

 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之前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; } 

上面,你的意思是不是和。 AND的例子:110&011 == 010这既不是你正在寻找的东西。

对于OR,一号有2个没有rest的情况。 例如:

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

以上都是优秀的答案。 我只是想补充说,当有多个字符要检查时,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 } 

当然,如果这变得更复杂,我会推荐一个正则expression式匹配器。

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

 Character.toLowerCase(c); 

观察一个有趣的Switch case陷阱 – > fall through switch

“break语句是必须的,因为如果没有它们,switch语句中的语句就会通过:” Java Doc的例子

break连续case片段:

  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

即使第二种情况下testing失败,程序也会进入打印A ,由于缺lessbreak而导致switch将代码的其余部分视为块。 匹配的case标签之后的所有语句按顺序执行。