Java switch case 语句问题
我正在尝试在 Android 应用程序中使用 switch 语句,其中我必须检查整数是否等于某些枚举的值。代码如下所示:
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");
}
}
}
我的 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;
}
}
}
但我收到错误消息:“类型不匹配:无法从 RPCCommucatorDefines.RPCServerResponseCode 转换为 int”。 有什么建议如何解决这个问题吗?提前致谢!!!
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!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
错误代码
是int
。应为 RPCServerResponseCode 类型,因此您可以使用类似以下内容的内容:errorcode
isint
. Should be of typeRPCServerResponseCode
, so you could use something like:您正在尝试将
INT
错误代码与RPCServerResponseCode
实例进行比较 - 这是不可能的。您需要使用RPCServerResponseCode
类中的方法getByValue
来为您进行转换。之后,您可以在 switch 语句中使用结果(这将是一个 RPCServerResponseCode 实例):You're trying to compare your
INT
error code to aRPCServerResponseCode
instance - This isn't possible. You need to use the methodgetByValue
in yourRPCServerResponseCode
class to do the conversion for you. After that, you can use the result (Which will be aRPCServerResponseCode
instance) in your switch statement:Java 枚举是成熟的对象,不能隐式转换为整数。
这应该有效:
Java enums are fully-fledged objects and cannot be implicitly cast to integers.
This should work:
你可以说
you can say