[英]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 : 我正在尝试在Android应用中使用switch语句,在这里我必须检查一个整数是否等于Enum的某些值。代码如下所示:
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 : 我的switch语句如下所示:
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". 但是我收到这样的错误消息:“类型不匹配:无法从RPCCommucatorDefines.RPCServerResponseCode转换为int”。 Any suggestions how to solce that issue?
有什么建议可以解决这个问题吗? Thanks in advance!!!
提前致谢!!!
errorcode
is int
. errorcode
为int
。 Should be of type RPCServerResponseCode
, so you could use something like: 应该是
RPCServerResponseCode
类型,因此您可以使用类似以下内容:
switch (RCPServerResponseCode.getByValue(errorcode))
{
...
}
You're trying to compare your INT
error code to a RPCServerResponseCode
instance - This isn't possible. 您正在尝试将
INT
错误代码与RPCServerResponseCode
实例进行比较-这是不可能的。 You need to use the method getByValue
in your RPCServerResponseCode
class to do the conversion for you. 您需要在
RPCServerResponseCode
类中使用方法getByValue
为您执行转换。 After that, you can use the result (Which will be a RPCServerResponseCode
instance) in your switch statement: 之后,您可以在switch语句中使用结果(将是
RPCServerResponseCode
实例):
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. Java枚举是成熟的对象,不能隐式转换为整数。
This should work: 这应该工作:
switch(RPCServerResponseCode.getByValue(errorCode)){
you can say 你可以说
int errorCode=4001;
RPCServerResponseCode code = RPCServerResponseCode.getByValue(errorCode);
switch(code){
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.