开发者

Java Switch Incompatible Types Boolean Int

开发者 https://www.devze.com 2022-12-31 05:21 出处:网络
I have the following class: public class NewGameContract { public boolean HomeNewGame = false; public boolean AwayNewGame = false;

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?


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.


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)


Switch statements in Java can use byte, short, char, and int (note: not long) primitive data types or their corresponding wrapper types. Starting with J2SE 5.0, it became possible to use enum types. Starting with Java SE 7, it became possible to use Strings.


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


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消