java - java中Switch语句中Integer类型的使用

标签 java switch-statement

<分区>

我正在为我的 Android 应用程序用 Java 编写一些简单的代码,但出现了这些错误。

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,然后我将类型更改为int,问题就解决了

我的问题是为什么我们不能使用 Integer 作为 case 表达式。 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"虽然变量是常数 我读了this question但没有得到任何东西

最佳答案

Constant expressions are used as case labels in switch statements ( §14.11 ) and have a special significance for assignment conversion ( §5.2 ) and .....

Definition of Constant Expression §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 实际上不是常量表达式编译器。

关于java - java中Switch语句中Integer类型的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26139028/

相关文章:

java - 更改现有应用程序的 admob id

javascript - 在 es6 中使用解构 switch 语句

c++ - switch/case 中定义的变量是否保留其值?

c - 为什么这个 switch case 程序在整数输入之后不接受字符输入?

java - JApplet 内的 JFrame

java - 使用额外传入的字符串调用 SQLiteOpenHelper

java - 是否有任何方便的代码覆盖工具可与 JUnit 一起使用?

java - JTable扩展后无法向下滚动?

c++ - 我可以使用开关来保持功能吗?

c++ - 为什么这段代码打印0223?