Java switch case statement issue
I'm trying to use a switch statement in Android aplication,where I have to check if an integer is equal to some of the Enum's value.The code goes like this :
public enum RPCServerResponseCode{
E_INCORRECT_LOGIN(4001),
E_ACCOUNT_DISABLED(4002),
E_ACCOUNT_NOT_ACTIVE(4003);
private int value;
private RPCServerResponseCode(int i) {
this.value=i;
}
public static RPCServerResponseCode getByValue(int i) {
for(RPCServerResponseCode dt : RPCServerResponseCode.values()) {
if(dt.value开发者_运维百科 == i) {
return dt;
}
}
throw new IllegalArgumentException("No datatype with " + i + " exists");
}
}
}
And my switch statement looks like this :
int errorCode;
switch(errorCode){
case RPCServerResponseCode.E_INCORRECT_LOGIN :
{
if (user.isAuthenticated)
{
// logout before login
}
break;
}
case RPCServerResponseCode.E_ACCOUNT_NOT_ACTIVE:
{
if (user.isAuthenticated)
{
//logout
}
break;
}
}
}
But I get error saying this : "Type mismatch: cannot convert from RPCCommucatorDefines.RPCServerResponseCode to int". Any suggestions how to solce that issue? Thanks in advance!!!
errorcode
is int
. Should be of type RPCServerResponseCode
, so you could use something like:
switch (RCPServerResponseCode.getByValue(errorcode))
{
...
}
You're trying to compare your INT
error code to a RPCServerResponseCode
instance - This isn't possible. You need to use the method getByValue
in your RPCServerResponseCode
class to do the conversion for you. After that, you can use the result (Which will be a RPCServerResponseCode
instance) in your switch statement:
int errorCode;
RPCServerResponseCode responseCode = RPCServerResponseCode.getByValue(errorCode);
switch(responseCode){
case RPCServerResponseCode.E_INCORRECT_LOGIN :
{
if (user.isAuthenticated)
{
// logout before login
}
break;
}
case RPCServerResponseCode.E_ACCOUNT_NOT_ACTIVE:
{
if (user.isAuthenticated)
{
//logout
}
break;
}
}
}
Java enums are fully-fledged objects and cannot be implicitly cast to integers.
This should work:
switch(RPCServerResponseCode.getByValue(errorCode)){
you can say
int errorCode=4001;
RPCServerResponseCode code = RPCServerResponseCode.getByValue(errorCode);
switch(code){
...
}
精彩评论