我实现了一个字体系统,它通过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中是可能的吗?
发布于 2012-03-27 11:45:52
您可以通过省略break;
语句来使用switch-case fall through。
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
ing之前,你可以将其标准化为lower case或upper 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;
}
发布于 2012-03-27 11:50:13
上面,你的意思是或者不是AND。和的例子: 110 & 011 == 010,这两个都不是你想要的。
对于OR,只有2个案例,在1号没有中断。例如:
case 'a':
case 'A':
// do stuff
break;
发布于 2012-03-27 15:45:35
以上都是很好的答案。我只是想补充一下,当有多个字符需要检查时,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
}
当然,如果这变得更复杂,我会推荐一个正则表达式匹配器。
https://stackoverflow.com/questions/9883113
复制相似问题