首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java Switch语句-“或”/“and”可能吗?

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

Stack Overflow用户
提问于 2012-03-27 11:44:50
回答 4查看 116.7K关注 0票数 81

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

代码语言:javascript
复制
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中是可能的吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-03-27 11:45:52

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

代码语言:javascript
复制
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;
}

switching之前,你可以将其标准化为lower caseupper case

代码语言:javascript
复制
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;
}
票数 211
EN

Stack Overflow用户

发布于 2012-03-27 11:50:13

上面,你的意思是或者不是AND。和的例子: 110 & 011 == 010,这两个都不是你想要的。

对于OR,只有2个案例,在1号没有中断。例如:

代码语言:javascript
复制
case 'a':
case 'A':
  // do stuff
  break;
票数 22
EN

Stack Overflow用户

发布于 2012-03-27 15:45:35

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

代码语言:javascript
复制
// 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
}

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

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9883113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档