Matteo
Matteo

Reputation: 8142

Switch Statement in Java will choose opposite case

I'm using a switch statement in a class's method that's called by another class.

The Switch statement gets as input a variable representing an enum type.

Called Class:

public class called_foo {

    public static enum ENUM_TYPE {
        TYPE2, TYPE1
    }

    public void method( ENUM_TYPE type ){

        switch( type ){

            case TYPE1: System.out.println("TYPE1");
                        break;

            case TYPE2: System.out.println("TYPE2");
                        break;

            default:    System.out.println("Error in retrieving Type");
                        System.exit(1);
        }
    }

}    

Calling Class:

public class calling_foo {

    public void run(){

        called_foo cf = new called_foo();
        cf.method( ENUM_TYPE.TYPE1 );
    }

    public static void main(String[] args) throws Exception {

        calling_foo f = new calling_foo();
        f.run();
    }

}

First Question: "Are there any errors in the syntax of these two classes?"

Second Question: "If not, why is output the opposite of what I'm expecting?"

Output:

if I call cf.method( ENUM_TYPE.TYPE1 ); I see on screen "TYPE2"
if I call cf.method( ENUM_TYPE.TYPE2 ); I see on screen "TYPE1"

Upvotes: 0

Views: 572

Answers (1)

TonioElGringo
TonioElGringo

Reputation: 1037

I can't manage to compile your code "as is". I think you have defined ENUM_TYPE another time in calling_foo, with TYPE1 and TYPE2 reversed, so that calling_foo.ENUM_TYPE.TYPE1 is actually the one used, and correspond to called_foo.ENUM_TYPE.TYPE2 .

You should specify that the ENUM_TYPE enumeration to use is actually called_foo.ENUM_TYPE.TYPE1 when you call cf.method. This way the code does compile and you get the expected result.

Upvotes: 1

Related Questions