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)
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)
Din*_*nah 18
以上,你的意思是OR而不是AND.AND的例子:110&011 == 010这不是你要找的东西.
对于OR,只有2个没有中断的情况.例如:
case 'a':
case 'A':
// do stuff
break;
Run Code Online (Sandbox Code Playgroud)
以上都是很好的答案.我只是想补充一点,当有多个字符要检查时,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)
当然,如果这变得更复杂,我建议使用正则表达式匹配器.