Java Switch不兼容的类型布尔Int

iTE*_*Egg 0 java boolean compiler-errors switch-statement

我有以下课程:

public class NewGameContract {

public boolean HomeNewGame = false;

public boolean AwayNewGame = false;

public boolean GameContract(){

    if (HomeNewGame && AwayNewGame){
        return true;
    } else {
        return false;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用它时:

            if (networkConnection){

            connect4GameModel.newGameContract.HomeNewGame = true;

            boolean status = connect4GameModel.newGameContract.GameContract();

            switch (status){

                case true:
                    break;

                case false:
                    break;
            }
            return;
        }
Run Code Online (Sandbox Code Playgroud)

我收到错误:

incompatible types found: boolean required: int on the following
`switch (status)` code.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

chr*_*ris 9

你不想switch在布尔上,只需使用一个简单的if/else

if (status) {
  ....
} else {
  ....
}
Run Code Online (Sandbox Code Playgroud)

编辑:switch仅用于intS,charS,或enumS(我认为这是所有的,也许还有其他?)编辑编辑:好像shortbyte也适用类型的切换,以及所有这些的盒装版本(Integer,Short,等等)

  • 哦,似乎java7甚至(最终)也包括支持切换String!好极了!http://tech.puredanger.com/java7/#switch (2认同)

pol*_*nts 9

你不能打开一个boolean(无论如何只有2个值):

Java语言规范明确指出了可以使用什么类型的表达式switch.

JLS 14.11 switch语句

SwitchStatement:
    switch ( Expression ) SwitchBlock
Run Code Online (Sandbox Code Playgroud)

该类型的Expression必须是char,byte,short,int,Character,Byte,Short,Integer,或enum类型,或编译时会出现误差.

简单地使用if语句来区分这两种情况,它更具可读性和简洁性boolean.