Java Switch Statement - Is "or"/"and" possible?
Asked Answered
S

6

86

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?

Sine answered 27/3, 2012 at 3:44 Comment(2)
I just want to point out that I haven't used the switch statement for ages and I program Java nearly every day. The reason is that I find it bad style because it is kind of a goto and there is always a different solution which I like better. In your case, you could use a Map or an enum (which is often a good replacement) with the methods boolean matches(char c) and File getImage()Monteiro
@MichaelSchmeißer In that case, then you might also want to reconsider using for/while loops too because they're another form of Goto /s. That's why they also contain break/continue keywords. In all seriousness, 'switch' is not goto because it provides its own block scope. It's just another tool in the toolbox and for this specific use case it's also the most appropriate.Hindbrain
J
218

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;
}
Jurisconsult answered 27/3, 2012 at 3:45 Comment(2)
Ah, thanks for that example. I thought of making the input string into all caps before but didn't know how possible it was so thanks for the second example too.Sine
Actually, on the off-chance the case of c needs to be preserved, I would put the toUpperCase inside the switch. But +1 since this saves a lot of lines of unnecessary case statements :-)Furtive
F
24

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;
Filamentary answered 27/3, 2012 at 3:50 Comment(2)
I don't know how helpful that first bit is to the OP.Jurisconsult
@MДΓΓБДLL: The comment about AND was showing why the OP wants OR rather than AND. The OR part is the same as the accepted answer so I hope it's relevant.Filamentary
L
7

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.

Ladner answered 27/3, 2012 at 7:45 Comment(3)
== 0 is not correct. That is saying "is c the first character of the string?", you probably want either >= 0 or != -1.Fruitful
@dbaupp: oops, you're right. I was thinking of compareTo() instead of indexOf(). Fixed.Ladner
Some of those tests can be replaced with existing methods from Character, such as the "is digit" case.Jurisconsult
S
4

Enhanced switch/ case / Switch with arrows syntax (Since Java 13):

char c;
switch (c) {
    case 'A', 'a' -> {} // c is either 'A' or 'a'.
    case ...
}
Semiprofessional answered 30/11, 2022 at 20:41 Comment(0)
P
2

Observations on an interesting Switch case trap --> fall through of switch

"The break statements are necessary because without them, statements in switch blocks fall through:" Java Doc's example

Snippet of consecutive case without break:

    char c = 'A';/* switch with lower case */;
    switch(c) {
        case 'a':
            System.out.println("a");
        case 'A':
            System.out.println("A");
            break;
    }

O/P for this case is:

A

But if you change value of c, i.e., char c = 'a';, then this get interesting.

O/P for this case is:

a A

Even though the 2nd case test fails, program goes onto print A, due to missing break which causes switch to treat the rest of the code as a block. All statements after the matching case label are executed in sequence.

Pachydermatous answered 25/2, 2016 at 9:23 Comment(0)
V
1

From what I understand about your question, before passing the character into the switch statement, you can convert it to lowercase. So you don't have to worry about upper cases because they are automatically converted to lower case. For that you need to use the below function:

Character.toLowerCase(c);
Verbenaceous answered 27/3, 2012 at 11:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.