Java Switch 语句 - 是“或"/“和"可能的?

2022-01-12 00:00:00 char switch-statement java

我实现了一个字体系统,它通过 char switch 语句找出要使用的字母.我的字体图像中只有大写字母.我需要做到这一点,例如,'a' 和 'A' 都具有相同的输出.与其将案件数量增加 2 倍,不如说是以下内容:

I implemented a font system that finds out which letter to use via char switch statements. There are only capital letters in my font image. I need to make it so that, for example, 'a' and 'A' both have the same output. Instead of having 2x the amount of cases, could it be something like the following:

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

Is this possible in java?

推荐答案

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

You can use switch-case fall through by omitting the break; statement.

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

...或者您可以规范化为 小写或大写 切换之前.

...or you could just normalize to lower case or upper case before switching.

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

相关文章