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;
}
Is this possible in java?
You can use switch-case fall through by omitting the break; statement. ...or you could just normalize to lower case or upper case before switch ing.
Answer 5562ce6c9113cb40db0002aaYou can't use “||” in case names. But you can use multiple case names without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a “break”. As a result these cases will share the same code.
switch expression can't be float, double or boolean.
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 switch
ing.
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; }
Above, you mean OR not AND. Example of AND: 110 & 011 == 010 which is neither of the things you're looking for.
For OR, just have 2 cases without the break on the 1st. Eg:
case 'a': case 'A': // do stuff break;
The above are all excellent answers. I just wanted to add that when there are multiple characters to check against, an if-else might turn out better since you could instead write the following.
// 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
}
Of course, if this gets any more complicated, I'd recommend a regex matcher.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With