views:

279

answers:

5

I have the following class:

public class NewGameContract {

public boolean HomeNewGame = false;

public boolean AwayNewGame = false;

public boolean GameContract(){

    if (HomeNewGame && AwayNewGame){
        return true;
    } else {
        return false;
    }
}
}

When I try to use it like so:

            if (networkConnection){

            connect4GameModel.newGameContract.HomeNewGame = true;

            boolean status = connect4GameModel.newGameContract.GameContract();

            switch (status){

                case true:
                    break;

                case false:
                    break;
            }
            return;
        }

I am getting the error:

incompatible types found: boolean required: int on the following
`switch (status)` code.

What am I doing wrong?

+9  A: 

you don't want to switch on a boolean, just use a simple if/else

if (status) {
  ....
} else {
  ....
}

edit : switch is only used for ints, chars, or enums (i think that's all, maybe there are others?) edit edit : it seems short and byte are also valid types for switching, as well as the boxed versions of all of these (Integer, Short, etc etc)

oedo
byte and short, and anything with a narrowing cast (long, float double)
John Smith
oh, and it seems that java7 might even (FINALLY) include support for switching on String too! yay! http://tech.puredanger.com/java7/#switch
oedo
+1  A: 

Can't use boolean in switch, only int. Please read the Java docs for the switch statement.

duffymo
+1  A: 

In Java, switch only works for byte, short, char, int and enum. For booleans you should use if/else as there are a very limited number of states.

Donal Boyle
+6  A: 

You can't switch on a boolean (which only have 2 values anyway):

The Java Language Specification clearly specifies what type of expression can be switch-ed on.

JLS 14.11 The switch statement

SwitchStatement:
    switch ( Expression ) SwitchBlock

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type, or a compile-time error occurs.

It is a lot more readable and concise to simply use an if statement to distinguish the two cases of boolean.

polygenelubricants
+1  A: 

Switch takes an integer value, and a boolean cannot be converted to an integer.

In java, a boolean is a type in its own right, and not implicitly convertible to any other type (except Boolean).

John Smith