maccers
maccers

Reputation: 33

char array used in switch statement

Why does my compiler get mad (Constant expression required) when I say:

final static char [] BASES = new char[]{'A', 'T', 'C', 'G'};
.
.
       char c= in.charAt(i);
            switch(c){
                case BASES[0] : break;
                case BASES[1] : packed =(char) (packed | 1); break;
                .
                .
                .
            }

but if I say:

final static char a ='A';
final static char t ='T';
         switch(c){
                case a : break;
                ...

it's happy? I feel like I'm being thick here. :-/

Upvotes: 3

Views: 1528

Answers (1)

assylias
assylias

Reputation: 328735

The argument to a case must be a constant, i.e. a primitive/string constant or literal or an enum constant. Your array is constant but not its content...

In your case, an enum would be indicated and the code below is an example of how you could write it. It puts all the logic linked to the bases in the enum which you can now reuse where you need to - you can add methods too. And the main code is now clean and easy to read.

Main code:

public static void main(String[] args) {
    String input = "ATC";
    char packed = 0;
    for (char c : input.toCharArray()) {
        Base base = Base.valueOf(String.valueOf(c));
        packed = base.getPacked(packed);
    }
}

And your enum would look like:

public enum Base {

    A {
        public char getPacked(char packed) {
            return packed;
        }
    }, T {
        public char getPacked(char packed) {
            return (char) (packed | 1);
        }
    }, C {
        public char getPacked(char packed) {
            return packed;
        }
    }, G {
        public char getPacked(char packed) {
            return packed;
        }
    };

    public abstract char getPacked(char packed);
}

Upvotes: 4

Related Questions