java中Switch语句中整数类型的使用
我在 java 中为我的 android 应用程序编写了一些简单的代码,但出现了这些错误.
I was writing some simple code in java for my android app and i got these errors.
case 表达式必须是常量表达式
,而 private static final Integer
是常量
private static final Integer INVALID_USER = 901;
private static final Integer SENDING_FAILED = 902;
private static final Integer OK = 903;
/*
*
* And some more project related declaration...
*
*/
switch (responseCode){
case INVALID_USER:
// logout
break;
case SENDING_FAILED:
//resend request
break;
case OK:
break;
}
这是因为我使用了Integer Type
,然后我将type改为int
,问题就解决了
This is because i used Integer Type
, then i changed type to int
and problem is solved
我的问题是为什么我们不能使用 Integer
作为案例表达式.Docs 说开关适用于 byte、short、char 和 int原始数据类型.它也适用于枚举类型(在 Enum Types 中讨论)、String 类和一些包装某些原始类型的特殊类:Character、Byte、Short 和 Integer" 尽管变量是常量我读了这个问题,但没有得到任何东西
My question is why we cant use Integer
as a case expression. Docs says " A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer" though variable is constant
I read this question but didnt get any thing
推荐答案
常量表达式用作 switch 语句中的 case 标签 (§14.11 )并且对赋值转换具有特殊意义(§5.2 ) 和.....
Constant expressions are used as case labels in switch statements ( §14.11 ) and have a special significance for assignment conversion ( §5.2 ) and .....
常量的定义表达式§15.28
编译时常量表达式是一个表示值的表达式原始类型或不突然完成的字符串.
A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly.
现在在上述场景中,编译器正在寻找 常量表达式,因为编译器在编译时应该知道它.如上所述 Integer
实际上不是常量表达式编译器.
Now in above scenario compiler is looking for constant expression as it should be know to the compiler at the compile time.As stated Integer
is actually not a constant Expression for the compiler.
相关文章