Error constant expression required java

Есть некий статистический метод который должен выполнять определенную деятельность. Упростив до максимума выглядит он подобным образом public class test { public static void main(String[] arg...

Есть некий статистический метод который должен выполнять определенную деятельность.
Упростив до максимума выглядит он подобным образом

public class test
{
    public static void main(String[] args) {

        int forTest = 1;
        test(forTest);

    }

    public static void test(int testValue) {
        int m;
        int n = 1;

        switch (testValue) {
            case n: {
                //todo
            }
        }
    }
}

На строке выбора case n: { возникает ошибка constant expression required.
Из-за чего возникает данная проблема?
Каким образом проектировать методы и классы для исключения возможности данной ошибки в будущем?

задан 26 фев 2016 в 16:18

abbath0767's user avatar

abbath0767abbath0767

1,4453 золотых знака15 серебряных знаков26 бронзовых знаков

У вас проблема не с проектированием, а с синтаксисом языка. После case может идти только константа, но не переменная:

switch (testValue) {
  case 1: {
    // todo
  }
}

Если к такому виду привести код нельзя — не заморачивайтесь и воспользуйтесь оператором if:

if (testValue == 1) {
  // todo
}

ответ дан 26 фев 2016 в 16:22

Pavel Mayorov's user avatar

Pavel MayorovPavel Mayorov

57.4k7 золотых знаков68 серебряных знаков140 бронзовых знаков

3

Используй «final» при декларировании:

public static void test(int testValue) {
        int m;
        final int n = 1;

        switch (testValue) {
            case n: {
                //todo
            }
        }
    }

@Pavel Mayorov: и почему он должен использовать «if», если «switch» быстрее?

ответ дан 30 сен 2018 в 9:02

Eugen's user avatar

Используй Kotlin язык. Мне помогло

for (File curFile : listOfFiles) {
        if (curFile.isDirectory()) {
            switch (curFile.getName()) {
                case String.valueOf(xls_xlsx): //сдесь проблема - xls_xlsx это тип Enum (константа)
                    break;
            }
        }
    }

Теперь я в IDEA создал файл Kotlin‘a.
Скопировал туда код Java (весь файл или только функцию). Соглашаюсь что трансформируй мне в Kotlin (ждем некоторое время)
И готово — код Kotlin‘a теперь мой такой (и без проблем константа моя есть в switch (т.е. в when)

for (curFile in listOfFiles!!) {
        if (curFile.isDirectory) {
            when (curFile.name) {
                xls_xlsx.toString() -> { //проблема решена. Компилируется.
                }
            }
        }
    }

Если не знали Kotlin, то возможно у вас появился вопрос «как вызывать теперь Котлин из Джавы? Это все сделали за вас. Берем гуглим и есть простые ответы.

Почему я пишу этот пост. Потому что я пишу под себя и для себя. Мне нужно удобство и простота кода. Я решил через Kotlin

ответ дан 13 июн 2017 в 18:59

Саша's user avatar

СашаСаша

31 бронзовый знак

1

I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn’t Foo.BA_ constant?

While they are constant from the perspective of any code that executes after the fields have been initialized, they are not a compile time constant in the sense required by the JLS; see §15.28 Constant Expressions for the specification of a constant expression1. This refers to §4.12.4 Final Variables which defines a «constant variable» as follows:

We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).

In your example, the Foo.BA* variables do not have initializers, and hence do not qualify as «constant variables». The fix is simple; change the Foo.BA* variable declarations to have initializers that are compile-time constant expressions.

In other examples (where the initializers are already compile-time constant expressions), declaring the variable as final may be what is needed.

You could change your code to use an enum rather than int constants, but that brings another couple of different restrictions:

  • You must include a default case, even if you have case for every known value of the enum; see Why is default required for a switch on an enum?
  • The case labels must all be explicit enum values, not expressions that evaluate to enum values.

1 — The constant expression restrictions can be summarized as follows. Constant expressions a) can use primitive types and String only, b) allow primaries that are literals (apart from null) and constant variables only, c) allow constant expressions possibly parenthesised as subexpressions, d) allow operators except for assignment operators, ++, -- or instanceof, and e) allow type casts to primitive types or String only.

Note that this doesn’t include any form of method or lambda calls, new, .class. .length or array subscripting. Furthermore, any use of array values, enum values, values of primitive wrapper types, boxing and unboxing are all excluded because of a).

Содержание

  1. switch statement: constant expression required error
  2. Оператор переключения Java: требуется постоянное выражение, но оно является постоянным
  3. Оператор переключения Java: требуется постоянное выражение, но оно ЯВЛЯЕТСЯ константой
  4. Constant expression required java
  5. Оператор switch Java: требуется постоянное выражение, но оно постоянное
  6. Constant expression required java
  7. Поддержка и обратная связь Support and feedback
  8. 3 ответа 3
  9. Всё ещё ищете ответ? Посмотрите другие вопросы с метками java или задайте свой вопрос.
  10. Похожие
  11. 13 Answers 13
  12. Constant expression required java
  13. Constant expression required java
  14. Ответы (10)
  15. Constant expression required java
  16. switch statement: constant expression r…
  17. java — Как обойти constant expression r…
  18. 【Java异常】 switch case出现Constant ex…
  19. Java Error: constant string expression req…
  20. java — what causes «constant expressio…
  21. Constant expression required_移动开发_c…
  22. 在java中,这样写switch语句有什么 …
  23. Java switch statement: Constant expressio…
  24. Constant expression required记一次switc…

switch statement: constant expression required error

  • Hi Ranchers!
    This morning I typed a very simple code:

    You can see that a,b and c should be compile time constants.
    But when I try to compile an error occurs:

    C:OCAswitch>javac Values.java
    Values.java:9: error: constant expression required
    case a:
    ^
    Values.java:12: error: constant expression required
    case b:
    ^
    Values.java:15: error: constant expression required
    case c:
    ^
    3 errors

    So for the compiler a,b and c are not constant. what’s going wrong?

  • Junilu Lacar wrote: Try declaring those constants as char instead of Character. See definition of constant variable here: https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.4

    Hi Junilu!
    I tried and it works.
    Thank you!

    But I wrote this code trying to prove one thing I read on the book on OCA (the Jeanne one, Sybex, at page 73), which states:

    Data types supported by switch statement incluede the following:
    — byte and Byte
    — short and Short
    — char and Character
    — int and Integer
    — String
    — enum Values

    But, if I undestood well, Character (. and probably the other mentioned Wrapper) cannot be a compile time constant in any way.
    So what’s the point in including them?

  • Junilu Lacar wrote: I think the book is referring to the switch part, not the case selectors.

    You are right Junilu.
    In fact the following compiles and runs as expercted:

    Now it’s clear for me too.

  • Values.java:9: error: constant expression required
    case a:
    ^
    Values.java:12: error: constant expression required
    case b:
    ^
    Values.java:15: error: constant expression required
    case c:
    ^
    3 errors[/b]

    Compiler is treating a,b and c as variable but there you need a constant expression for the data type you provide in your switch label. In your case ‘A’ ‘B’ and ‘C’ instead a b and c or any other character constant according to your need.

  • adita malviya wrote:
    Compiler is treating a,b and c as variable but there you need a constant expression for the data type you provide in your switch label. In your case ‘A’ ‘B’ and ‘C’ instead a b and c or any other character constant according to your need.

    OK, but the code treated a,b and c as constants.
    I wanted to try to use Character wrappers as constants, not directly literals.

    This code helped me to understand the scope of the wrappers usage in the swich statetement.
    It appears that the wrappers can be used in the swich expression BUT NOT as in case constant as constants, where you’re forced to use char primitive instead.

    Источник

    Оператор переключения Java: требуется постоянное выражение, но оно является постоянным

    Итак, я работаю над этим классом, который имеет несколько статических констант:

    Затем я хотел бы получить способ получить соответствующую строку на основе константы:

    Однако, когда я компилирую, я получаю сообщение constant expression required об ошибке на каждой из трех меток регистра.

    Я понимаю, что компилятору нужно, чтобы выражение было известно во время компиляции, чтобы скомпилировать ключ, но почему не Foo.BA_ константа?

    Я понимаю, что для компиляции переключателя необходимо, чтобы выражение было известно во время компиляции, но почему Foo.BA_ не является константой?

    Хотя они являются постоянными с точки зрения любого кода, который выполняется после инициализации полей, они не являются постоянной времени компиляции в том смысле, который требуется JLS; см. §15.28 Выражения констант для спецификации константного выражения 1 . Это относится к §4.12.4 Final Variables, который определяет «постоянную переменную» следующим образом:

    Мы называем переменную примитивного типа или типа String, которая является окончательной и инициализируется с помощью константного выражения времени компиляции (§15.28) постоянной переменной. Независимо от того, является ли переменная постоянной или нет, это может иметь последствия в отношении инициализации класса (§12.4.1), двоичной совместимости (§13.1, §13.4.9) и определенного присваивания (§16).

    В вашем примере переменные Foo.BA * не имеют инициализаторов и, следовательно, не квалифицируются как «постоянные переменные». Исправление просто; измените объявления переменных Foo.BA *, чтобы инициализаторы были константными выражениями во время компиляции.

    В других примерах (где инициализаторы уже являются константными выражениями времени компиляции), объявление переменной final может быть тем, что необходимо.

    Вы могли бы изменить свой код, чтобы использовать enum вместо int констант, но это приносит еще пару ограничений:

    • Вы должны включить default регистр, даже если у вас есть case для каждого известного значения enum ; см. Почему по умолчанию требуется для включения перечисления?
    • Все case метки должны быть явными enum значениями, а не выражениями, которые оценивают enum значения.

    1 — Ограничения константного выражения могут быть обобщены следующим образом. Выражения констант а) могут использовать только примитивные типы String , б) разрешать основные цвета, которые являются литералами (кроме null ) и только постоянными переменными, в) разрешать константные выражения, возможно заключенные в скобки как подвыражения, г) разрешать операторы, кроме операторов присваивания ++ , — или instanceof , и д) разрешить приведение типов к примитивным типам или String только.

    Обратите внимание , что это не относится к какой — либо форме метода или лямбда — вызовов new , .class . .length или массив подписки. Кроме того, любое использование значений массива, enum значений, значений типов примитивных оболочек, упаковки и распаковки исключено из-за a).

    Источник

    Оператор переключения Java: требуется постоянное выражение, но оно ЯВЛЯЕТСЯ константой

    Итак, я работаю над этим классом, который имеет несколько статических констант:

    Затем я хотел бы получить соответствующую строку на основе константы:

    Однако при компиляции я получаю сообщение constant expression required об ошибке на каждой из трех меток case.

    Я понимаю, что компилятору необходимо, чтобы выражение было известно во время компиляции для компиляции переключателя, но почему не является Foo.BA_ постоянным?

    I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn’t Foo.BA_ constant?

    Хотя они постоянны с точки зрения любого кода, который выполняется после инициализации полей, они не являются константой времени компиляции в том смысле, который требует JLS; см. §15.28 Постоянные выражения для определения константного выражения 1 . Это относится к §4.12.4 Final Variables, который определяет «постоянную переменную» следующим образом:

    We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).

    В вашем примере переменные Foo.BA * не имеют инициализаторов и, следовательно, не квалифицируются как «постоянные переменные». Исправить просто; измените объявления переменных Foo.BA * на инициализаторы, которые являются выражениями констант времени компиляции.

    В других примерах (где инициализаторы уже являются выражениями констант времени компиляции) объявление переменной final может быть тем, что необходимо.

    Вы можете изменить свой код, чтобы использовать enum вместо int констант, но это дает еще пару различных ограничений:

    • Вы должны указать default случай, даже если case для каждого известного значения enum ; см. Почему по умолчанию требуется переключатель в перечислении?
    • Все case метки должны быть явными enum значениями, а не выражениями, оценивающими enum значения.

    1 — Ограничения постоянного выражения можно резюмировать следующим образом. Константные выражения а) можно использовать примитивные типы и String только, б) позволяют праймериз , которые являются литералами (кроме null ) и постоянных переменный только, с) позволяют константные выражения , возможно , в скобках , как подвыражения, д) позволяют оператор для операторов присваивания , за исключением, ++ , — или instanceof , и e) разрешить приведение типов String только к примитивным типам .

    Обратите внимание , что это не относится к какой — либо форме метода или лямбда — вызовов new , .class . .length или индексирование массива. Более того, любое использование значений массива, enum значений, значений примитивных типов оболочки, упаковки и распаковки исключается из-за а).

    Источник

    Constant expression required java

    Оператор switch Java: требуется постоянное выражение, но оно постоянное

    Итак, я работаю над этим классом, который имеет несколько статических констант:

    Затем я хотел бы получить соответствующую строку на основе константы:

    Однако, когда я компилирую, я получаю ошибку constant expression required для каждой из трех меток case.

    Я понимаю, что компилятору нужно, чтобы во время компиляции было известно, что компилятор должен быть скомпилирован, но почему нет Foo.BA_ constant?

    Я понимаю, что для компиляции переключателя нужно, чтобы выражение было известно во время компиляции, но почему не константа Foo.BA_?

    Хотя они являются постоянными с точки зрения любого кода, который выполняется после инициализации полей, они не являются постоянной времени компиляции в том смысле, который требуется JLS; см. §15.28 Выражения констант для определения константного выражения 1 . Это относится к §4.12.4 конечным переменным, который определяет «постоянную переменную» следующим образом:

    Мы называем переменную примитивного типа или типа String, которая является окончательной и инициализируется с помощью константного выражения времени компиляции (§15.28) постоянной переменной. Независимо от того, является ли переменная постоянной или нет, это может иметь последствия в отношении инициализации класса (§12.4.1), двоичной совместимости (§13.1, §13.4.9) и определенного присваивания (§16).

    В вашем примере переменные Foo.BA * не имеют инициализаторов и, следовательно, не квалифицируются как «постоянные переменные». Исправление просто; измените объявления переменных Foo.BA *, чтобы инициализаторы представляли собой константные выражения во время компиляции.

    В других примерах (где инициализаторы уже являются константными выражениями времени компиляции), объявление переменной как final может быть тем, что необходимо.

    Вы можете изменить свой код, чтобы использовать константы enum , а не int , но это приводит к еще нескольким ограничениям:

    • Вы должны включить регистр default , даже если у вас есть case для каждого известного значения enum ; см. Почему по умолчанию требуется для включения перечисления?
    • Все метки case должны быть явными значениями enum , а не выражениями, которые оценивают значения enum .

    1 — The constant expression restrictions can be summarized as follows. Constant expressions a) can use primitive types and [TG49] only, b) allow primaries that are literals (apart from [TG410]) and constant variables only, c) allow constant expressions possibly parenthesised as subexpressions, d) allow operators except for assignment operators, [TG411], [TG412] or [TG413], and e) allow type casts to primitive types or [TG414] only.

    Note that this does not include any form of method or lambda calls, [TG415], [TG416]. [TG417] or array subscripting. Furthermore, any use of array values, [TG418] values, values of primitive wrapper types, boxing and unboxing are all excluded because of a).

    Constant expression required java

    Константа должна быть инициализирована. A constant must be initialized. Эта ошибка имеет следующие причины и решения: This error has the following causes and solutions:

    Вы попытались инициализировать константу с помощью переменной, экземпляра пользовательского типа, объекта или возвращаемого значения вызова функции. You tried to initialize a constant with a variable, an instance of a user-defined type, an object, or the return value of a function call.

    Инициализируйте константы с литералами, ранее объявленными константами, литералами и константами, соединяемыми операторами (за исключением логического оператора is ). Initialize constants with literals, previously declared constants, or literals and constants joined by operators (except the Is logical operator).

    Чтобы объявить динамический массив в процедуре, объявите массив с помощью оператора ReDim и укажите количество элементов с переменной. To declare a dynamic array within a procedure, declare the array with ReDim and specify the number of elements with a variable.

    Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh). For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

    Поддержка и обратная связь Support and feedback

    Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь. Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

    Есть некий статистический метод который должен выполнять определенную деятельность. Упростив до максимума выглядит он подобным образом

    3 ответа 3

    У вас проблема не с проектированием, а с синтаксисом языка. После case может идти только константа, но не переменная:

    Если к такому виду привести код нельзя — не заморачивайтесь и воспользуйтесь оператором if :

    Используй «final» при декларировании:

    @Pavel Mayorov: и почему он должен использовать «if», если «switch» быстрее?

    Используй Kotlin язык. Мне помогло

    Теперь я в IDEA создал файл Kotlin ‘a. Скопировал туда код Java (весь файл или только функцию). Соглашаюсь что трансформируй мне в Kotlin (ждем некоторое время) И готово — код Kotlin ‘a теперь мой такой (и без проблем константа моя есть в switch (т.е. в when )

    Если не знали Kotlin , то возможно у вас появился вопрос «как вызывать теперь Котлин из Джавы? Это все сделали за вас. Берем гуглим и есть простые ответы.

    Почему я пишу этот пост. Потому что я пишу под себя и для себя. Мне нужно удобство и простота кода. Я решил через Kotlin

    Всё ещё ищете ответ? Посмотрите другие вопросы с метками java или задайте свой вопрос.

    Похожие

    Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

    дизайн сайта / логотип © 2020 Stack Exchange Inc; пользовательское содержимое попадает под действие лицензии cc by-sa 4.0 с указанием ссылки на источник. rev 2020.1.10.35756

    So, I am working on this class that has a few static constants:

    Then, I would like a way to get a relevant string based on the constant:

    However, when I compile, I get a constant expression required error on each of the 3 case labels.

    I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn’t Foo.BA_ constant?

    13 Answers 13

    I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn’t Foo.BA_ constant?

    While they are constant from the perspective of any code that executes after the fields have been initialized, they are not a compile time constant in the sense required by the JLS; see §15.28 Constant Expressions for the specification of a constant expression 1 . This refers to §4.12.4 Final Variables which defines a «constant variable» as follows:

    We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).

    In your example, the Foo.BA* variables do not have initializers, and hence do not qualify as «constant variables». The fix is simple; change the Foo.BA* variable declarations to have initializers that are compile-time constant expressions.

    In other examples (where the initializers are already compile-time constant expressions), declaring the variable as final may be what is needed.

    You could change your code to use an enum rather than int constants, but that brings another couple of different restrictions:

    • You must include a default case, even if you have case for every known value of the enum ; see Why is default required for a switch on an enum?
    • The case labels must all be explicit enum values, not expressions that evaluate to enum values.

    1 — The constant expression restrictions can be summarized as follows. Constant expressions a) can use primitive types and String only, b) allow primaries that are literals (apart from null ) and constant variables only, c) allow constant expressions possibly parenthesised as subexpressions, d) allow operators except for assignment operators, ++ , — or instanceof , and e) allow type casts to primitive types or String only.

    Note that this doesn’t include any form of method or lambda calls, new , .class . .length or array subscripting. Furthermore, any use of array values, enum values, values of primitive wrapper types, boxing and unboxing are all excluded because of a).

    Constant expression required java

    Hi Ranchers!
    This morning I typed a very simple code:

    You can see that a,b and c should be compile time constants.
    But when I try to compile an error occurs:

    C:OCAswitch>javac Values.java
    Values.java:9: error: constant expression required
    case a:
    ^
    Values.java:12: error: constant expression required
    case b:
    ^
    Values.java:15: error: constant expression required
    case c:
    ^
    3 errors

    So for the compiler a,b and c are not constant. what’s going wrong?

    Junilu Lacar wrote: Try declaring those constants as char instead of Character. See definition of constant variable here: https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.4

    Hi Junilu!
    I tried and it works.
    Thank you!

    But I wrote this code trying to prove one thing I read on the book on OCA (the Jeanne one, Sybex, at page 73), which states:

    Data types supported by switch statement incluede the following:
    — byte and Byte
    — short and Short
    — char and Character
    — int and Integer
    — String
    — enum Values

    But, if I undestood well, Character (. and probably the other mentioned Wrapper) cannot be a compile time constant in any way.
    So what’s the point in including them?

    Junilu Lacar wrote: I think the book is referring to the switch part, not the case selectors.

    You are right Junilu.
    In fact the following compiles and runs as expercted:

    Now it’s clear for me too.

    Values.java:9: error: constant expression required
    case a:
    ^
    Values.java:12: error: constant expression required
    case b:
    ^
    Values.java:15: error: constant expression required
    case c:
    ^
    3 errors[/b]

    Compiler is treating a,b and c as variable but there you need a constant expression for the data type you provide in your switch label. In your case ‘A’ ‘B’ and ‘C’ instead a b and c or any other character constant according to your need.

    adita malviya wrote:
    Compiler is treating a,b and c as variable but there you need a constant expression for the data type you provide in your switch label. In your case ‘A’ ‘B’ and ‘C’ instead a b and c or any other character constant according to your need.

    OK, but the code treated a,b and c as constants.
    I wanted to try to use Character wrappers as constants, not directly literals.

    This code helped me to understand the scope of the wrappers usage in the swich statetement.
    It appears that the wrappers can be used in the swich expression BUT NOT as in case constant as constants, where you’re forced to use char primitive instead.

    Junilu Lacar wrote: I think the book is referring to the switch part, not the case selectors.

    Agreed since the book clearly explains The values in each case statement must be compile-time constant values of the same data type as the switch value under the heading of Compile-time Constant values.

    Constant expression required java

    151001 просмотра

    10 ответа

    14682 Репутация автора

    Итак, я работаю над этим классом, который имеет несколько статических констант:

    Затем я хотел бы получить соответствующую строку на основе константы:

    Однако, когда я компилирую, я получаю сообщение constant expression required об ошибке на каждой из трех меток.

    Я понимаю, что компилятору нужно знать во время компиляции выражение для компиляции ключа, но почему оно не является Foo.BA_ постоянным?

    Ответы (10)

    122 плюса

    509467 Репутация автора

    Я понимаю, что компилятору требуется выражение, которое должно быть известно во время компиляции, для компиляции ключа, но почему Foo.BA_ не константа?

    Хотя они являются постоянными с точки зрения любого кода, который выполняется после того, как поля были инициализированы, они не являются постоянной времени компиляции в смысле, требуемом JLS; см. § 15.28. Константные выражения для определения того, что требуется для постоянного выражения. Это относится к §4.12.4 Конечные переменные, которые определяют «постоянную переменную» следующим образом:

    Мы называем переменную примитивного типа или типа String, которая является окончательной и инициализируется постоянным выражением времени компиляции (§15.28) постоянной переменной. Независимо от того, является ли переменная постоянной или нет, она может иметь последствия для инициализации класса (§12.4.1), бинарной совместимости (§13.1, §13.4.9) и определенного назначения (§16).

    В вашем примере переменные Foo.BA * не имеют инициализаторов и, следовательно, не квалифицируются как «постоянные переменные». Исправить это просто; измените объявления переменных Foo.BA * на наличие инициализаторов, которые являются постоянными выражениями времени компиляции.

    26 плюса

    2660 Репутация автора

    Потому что это не константы времени компиляции. Рассмотрим следующий допустимый код:

    Вы можете знать только значение BAR во время выполнения.

    65 плюса

    8137 Репутация автора

    Вы получаете выражение Constant, потому что вы оставили значения вне своих констант. Пытаться:

    15 плюса

    1128 Репутация автора

    Вы можете использовать перечисление, как в этом примере:

    5598 Репутация автора

    Я рекомендую использовать перечисления 🙂

    Затем вы можете использовать его следующим образом:

    Автор: everton Размещён: 21.07.2011 05:18

    34 плюса

    3873 Репутация автора

    Я получил эту ошибку на Android, и мое решение было просто использовать:

    Автор: Teo Inke Размещён: 25.02.2015 09:16

    562 Репутация автора

    Это было отвечено много лет назад и, вероятно, не имеет значения, но на всякий случай. Когда я столкнулся с этой проблемой, я просто использовал if инструкцию вместо switch нее, она решила ошибку

    629 Репутация автора

    Иногда переменная switch также может сделать эту ошибку, например:

    Чтобы решить эту проблему, нужно перечислить переменную в int (в данном случае). Так:

    Автор: Malv Размещён: 14.05.2018 07:58

    15158 Репутация автора

    Получил эту ошибку в Android, делая что-то вроде этого:

    несмотря на объявление константы:

    public static final String ADMIN_CONSTANT= «Admin»;

    Я решил проблему, изменив код:

    458 Репутация автора

    В моем случае я получал это исключение, потому что

    Constant expression required java

    Перевести · I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn’t Foo.BA_ constant? While they are constant from the perspective of any code that executes after the fields have been initialized, they are not a compile time constant in the sense required by the JLS; see §15.28 Constant Expressions for the specification of a constant expression 1.

    switch statement: constant expression r…

    Перевести · Values.java:9: error: constant expression required case a: ^ Values.java:12: error: constant expression required case b: ^ Values.java:15: error: constant expression required case c: ^ 3 errors[/b] Compiler is treating a,b and c as variable but there you need a constant expression

    java — Как обойти constant expression r…

    【Java异常】 switch case出现Constant ex…

    Перевести · 10.01.2018 · 今天使用switch case时突然出现了Constant expression required JavaJava异常】 switch case出现Constant expression required. . 后续我查了一下资料 switch case支持的类型: byte,short,char,int, 枚举类型,java.lang.String.

    Java Error: constant string expression req…

    Перевести · You should not mix up program logic and user interface texts. The action command is a property …

    java — what causes «constant expressio…

    Перевести · We’ve got a multi-project app that we’re moving to gradle. The build results in Java compilation errors like: AFragment.java:159: constant expression required case R.id.aBtn: We’ve confirmed that the constants reported in errors are in the generated R.java

    Constant expression required_移动开发_c…

    Перевести · 01.12.2016 · constant expression required这个异常的意思必须声明为常量,常量有个特定那就是不变的,此时需要final修饰那我们就将Constant 类 . 【Java异常】 switch case出现Constant expression required问题解决依据:switch case支持的类型:byte . public static final String

    在java中,这样写switch语句有什么 …

    Перевести · 07.04.2017 · 【Java异常】 switch case出现Constant expression requiredJava异常】 switch case出现Constant expression required 问题解决依据:switch case支持的类型:byte,short,char,int,枚举类型,java.lang.String

    Java switch statement: Constant expressio

    Перевести · I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn’t Foo.BA_ constant? While they are constant from the perspective of any code that executes after the fields have been initialized, they are not a compile time constant in the sense required by the JLS; see §15.28 Constant Expressions for a definition of what is required

    Constant expression required记一次switc…

    Перевести · Constant expression required记一次switch结合Enum的使用. 首先. switch的case只能使用常 …

    Источник


    switch statement: constant expression required error


    posted 5 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Hi Ranchers!

    This morning I typed a very simple code:

    You can see that a,b and c should be compile time constants.

    But when I try to compile an error occurs:

    C:OCAswitch>javac Values.java

    Values.java:9: error: constant expression required

                                   case a:

                                        ^

    Values.java:12: error: constant expression required

                                   case b:

                                        ^

    Values.java:15: error: constant expression required

                                   case c:

                                        ^

    3 errors

    So for the compiler a,b and c are not constant…what’s going wrong?

    Daniele Barell

    Ranch Hand

    Posts: 95


    posted 5 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Junilu Lacar wrote:Try declaring those constants as char instead of Character. See definition of constant variable here: https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.4

    Hi Junilu!

    I tried and it works.

    Thank you!

    But I wrote this code trying to prove one thing I read on the book on OCA (the Jeanne one, Sybex, at page 73), which states:

    Data types supported by switch statement incluede the following:

    — byte and Byte

    — short and Short

    — char and Character

    — int and Integer

    — String

    — enum Values

    But, if I undestood well, Character (…and probably the other mentioned Wrapper) cannot be a compile time constant in any way.

    So what’s the point in including them?


    posted 5 years ago


    • Likes 1
    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    I think the book is referring to the switch part, not the case selectors.

    Daniele Barell

    Ranch Hand

    Posts: 95


    posted 5 years ago


    • Likes 1
    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Junilu Lacar wrote:I think the book is referring to the switch part, not the case selectors.

    You are right Junilu.

    In fact the following compiles and runs as expercted:

    Now it’s clear for me too.

    Thanks again!


    posted 5 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Values.java:9: error: constant expression required

                                   case a:

                                        ^

    Values.java:12: error: constant expression required

                                   case b:

                                        ^

    Values.java:15: error: constant expression required

                                   case c:

                                        ^

    3 errors[/b]

    Compiler is treating a,b and c as variable but there you need a constant expression for the data type you provide in your switch label. In your case ‘A’ ‘B’ and ‘C’ instead a b and c or any other character constant according to your need.

    Daniele Barell

    Ranch Hand

    Posts: 95


    posted 5 years ago


    • Likes 1
    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    adita malviya wrote:

    Compiler is treating a,b and c as variable but there you need a constant expression for the data type you provide in your switch label. In your case ‘A’ ‘B’ and ‘C’ instead a b and c or any other character constant according to your need.

    Hi adita.

    OK, but the code treated a,b and c as constants.

    I wanted to try to use Character wrappers as constants, not directly literals.

    This code helped me to understand the scope of the wrappers usage in the

    swich statetement

    .

    It appears that the wrappers can be used in the

    swich

    expression BUT NOT as in

    case

    constant as constants, where you’re forced to use char primitive instead.

    Marshal

    Posts: 77296


    posted 5 years ago


    • Likes 1
    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Yes, as somebody said yesterday, a Character object doesn’t count as a constant expression. Remind yourself about what constitutes a constant expression in the Java® Language Specification.


    posted 5 years ago


    • Likes 1
    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Junilu Lacar wrote:I think the book is referring to the switch part, not the case selectors.

    Agreed since the book clearly explains The values in each case statement must be compile-time constant values of the same data type as the switch value under the heading of Compile-time Constant values.

    Не компилит

    Возмущается на конструкцию switch. Конкретнее, ему не нравится ClassName.class.getSimpleName(). Я так понимаю, что таким образом я возвращаю простое имя класса(без пакетов), тоже самое возвращается и в условии значения switch, и switch проверяет их через equal?
    Где я тут ошибаюсь?

    package com.javarush.task.task12.task1225;

    /*
    Посетители
    */

    public class Solution {
    public static void main(String[] args) {
    System.out.println(getObjectType(new Cat()));
    System.out.println(getObjectType(new Tiger()));
    System.out.println(getObjectType(new Lion()));
    System.out.println(getObjectType(new Bull()));
    System.out.println(getObjectType(new Cow()));
    System.out.println(getObjectType(new Animal()));
    }

    public static String getObjectType(Object o) {
    switch (o.getClass().getSimpleName()){
    case Cat.class.getSimpleName():
    return «Кот»;
    break;
    case Tiger.class.getSimpleName():
    return «Тигр»;
    break;
    case Lion.class.getSimpleName():
    return «Лев»;
    break;
    case Bull.class.getSimpleName():
    return «Бык»;
    break;
    case Cow.class.getSimpleName():
    return «Корова»;
    break;
    case Animal.class.getSimpleName():
    return «Животное»;
    break;
    }
    }

    public static class Cat extends Animal //<—Классы наследуются!!
    {
    }

    public static class Tiger extends Cat {
    }

    public static class Lion extends Cat {
    }

    public static class Bull extends Animal {
    }

    public static class Cow extends Animal {
    }

    public static class Animal {
    }
    }

    Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

    A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

    Syntax

    switch(expression) {
       case value :
          // Statements
          break;
       case value :
          // Statements
          break;
          // You can have any number of case statements.
       default :
          // Statements
    }

    Rules to be followed

    While working with a switch statement keep the following points in mind −

    • We must only use int, char or, enum types along with switch. Usage of any other types generates a compile time error.

    Example

    import java.util.Scanner;
    public class SwitchExample {
       public static void main(String args[]) {
          Scanner sc = new Scanner(System.in);
          System.out.println("Enter percentage: ");
          float percent = sc.nextFloat();
          switch (percent) {
             case (percent>=80):
                System.out.println("A Grade");
                break;
             case (percent<80):
                System.out.println("Not A Grade");
                break;
          }
       }
    }

    Compile time error

    SwitchExample.java:7: error: incompatible types: possible lossy conversion from float to int
       switch (percent) {
    ^
    SwitchExample.java:8: error: constant expression required
       case (percent>=80):
    ^
    SwitchExample.java:11: error: constant expression required
    case (percent<80):
    ^
    3 errors

    If you compile the above program in eclipse it shows a message as shown below −

    All the statements in a switch case are executed until they reach a break statement. Therefore, you need to have break after every case else all the cases will be executed irrespective of the option you choose.

    Example

     Live Demo

    import java.util.Scanner;
    public class SwitchExample {
       public static void main(String args[]) {
          Scanner sc = new Scanner(System.in);
          System.out.println("Available models: Activa125(act125), Activa5G(act5g)," + " Accesses125(acc125), Vespa(ves), TvsJupiter(jup)");
          System.out.println("Select one model: ");
          String model = sc.next();
          switch (model) {
             case "act125":
                System.out.println("The price of activa125 is 80000");
                //break;
             case "act5g":
                System.out.println("The price of activa5G is 75000");
                //break;
             case "acc125":
                System.out.println("The price of access125 is 70000");
                //break;
             case "ves125":
                System.out.println("The price of vespa is 90000");
                //break;
             case "jup":
                System.out.println("The price of tvsjupiter is 73000");
                //break;
             default:
                System.out.println("Model not found");
                break;
          }
       }
    }

    Output

    Available models: Activa125(act125), Activa5G(act5g), Accesses125(acc125), Vespa(ves), TvsJupiter(jup)
    Select one model:
    act125
    The price of activa125 is 80000
    The price of activa5G is 75000
    The price of access125 is 70000
    The price of vespa is 90000
    The price of tvsjupiter is 73000
    Model not found

    Expressions we use in the switch statement must be constant, if we use other expressions a compile time error will be generated.

    Example

    import java.util.Scanner;
    public class SwitchExample {
       public static void main(String args[]) {
          Scanner sc = new Scanner(System.in);
          String str[] = {"act125", "act5g", "acc125"};
          System.out.println("Available models: Activa125(act125), Activa5G(act5g), Accesses125(acc125)");
          System.out.println("Select one model: ");
          String model = sc.next();
          switch (model) {
             case str[0]:
                System.out.println("The price of activa125 is 80000");
                break;
             case str[1]:
                System.out.println("The price of activa5G is 75000");
                break;
             case str[2]:
                System.out.println("The price of access125 is 70000");
                break;
          }
       }
    }

    Output

    SwitchExample.java:10: error: constant string expression required
       case str[0]:
               ^
    SwitchExample.java:13: error: constant string expression required
       case str[1]:
               ^
    SwitchExample.java:16: error: constant string expression required
        case str[2]:
                ^
    3 errors

    Two cases Must not have same value. If so, a compile time error will be generated.

    Example

    import java.util.Scanner;
    public class SwitchExample {
       public static void main(String args[]) {
          Scanner sc = new Scanner(System.in);
          String str[] = {"act125", "act5g", "acc125"};
          System.out.println("Available models: Activa125(act125), Activa5G(act5g), Accesses125(acc125)");
          System.out.println("Select one model: ");
          String model = sc.next();
          switch (model) {
             case "act125":
                System.out.println("The price of activa125 is 80000");
                break;
             case "act125":
                System.out.println("The price of activa5G is 75000");
                break;
             case "acc125":
                System.out.println("The price of access125 is 70000");
                break;
          }
       }
    }

    Compile time error

    SwitchExample.java:13: error: duplicate case label
       case "act125":
       ^
    1 error

    You can have the default statement anywhere and, statements above cases never gets executed.

    Hey.

    I have this method:

    private static String convertDayToString(int day) {
            Calendar c = Calendar.getInstance();
            switch (day) {
            case c.SUNDAY:
                return "Sunday";
            case c.MONDAY:
                return "Monday";
            case c.TUESDAY:
                return "Tuesday";
            case c.WEDNESDAY:
                return "Wednesday";
            case c.THURSDAY:
                return "Thursday";
            case c.FRIDAY:
                return "Friday";
            case c.SATURDAY:
                return "Saturday";
            }
            return "UnknownDay";
        }

    It should return a String representation of a day based on the passed int argument, gotten via Calendar.DAY, Calendar.DAY_OF_MONTH, Calendar.DAY_OF_YEAR, etc.

    Basically, this is what I want it to do:

    System.out.println("The current day is: " + convertDayToString(Calendar.getInstance().DAY_OF_MONTH));
    -- "The current day is: Wednesday"

    I think it is created correctly… but there’s a compiler error I’ve never seen before, and it has to do with Switch Statements, which I don’t use all that often.

    constant expression required at line xx

    It flags the first case line

    case c.SUNDAY:
                return "Sunday";

    So I changed it to

    case 1:
                return "Sunday";

    And it flagged the next case line, thus leading me to believe…
    Can constants not be used in switch statements?

    Edited by: LukeFoss on Oct 24, 2007 9:38 AM

    Edited by: LukeFoss on Oct 24, 2007 9:40 AM

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Error confidence value 227
  • Error confidence value 172
  • Error conf phpmyadmin does not exist
  • Error condition ribbon out zebra 105sl как исправить
  • Error compiling template invalid expression invalid or unexpected token in

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии