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 bechar
,byte
,short
,int
,Character
,Byte
,Short
,Integer
, or anenum
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 int
s, char
s, or enum
s (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.
精彩评论