Case Expressions must be Constant expressions

So I get this error: "case expressions must be constant expressions" When I run this code:

    switch(int(character)) {
      case int("a"):
      case int("A"):

I'm converting the strings to primitives, why doesn't it work in the switch/case format?

Answers

  • Not the full code btw. I know it's a snippet.

  • edited March 2014
    case 'a':
    case 'A':
    

    should work.

    you've got a method where it's expecting a constant. it needs to know the value at compile time but it can't if this is a method (even a simple one like int())

    (int(i) is a processing method for casting a value, the java equiv would be (int)i. i've never liked this.)

  • edited March 2014

    int() is a Processing's function. While (int) is a native Java cast operator.

    And as @koogs has mentioned above, Java gotta know the switch () expression at compile time! @-)
    Java compiler won't run function int() at so early stage in order to statically establish the result as a known compiler literal! :P

    Who knows some1 might invent an über Java compiler which can guess compiler constants outta some standard math functions.
    Like sin(), sqrt(), round(), etc.! ^_^

    I prefer the native operator for most primitive type conversions though.
    However for more complex conversions, like String and whole arrays, we gotta use int()! :P

  • So, some of the strings I'm checking are multiple letters long. I looked at the reference for "int()", and it says it will convert strings to integers.

  • Well, I decided I'm just going to use an if/else if structure. For every letter of the alphabet... sigh...

  • edited March 2014 Answer ✓

    So, some of the strings I'm checking are multiple letters long.

    You haven't hinted that your question was String related. We all thought it was char primitives?! :O)

    Java 7+ accepts literal String constants for switch () / case : commands!
    So there's no need to convert them. Just make sure their values can be determined at compile time! :-SS

  • "Well, I decided I'm just going to use an if/else if structure. For every letter of the alphabet... sigh..."
    If you explain what is your problem, we probably can give a better (less typing!) solution...

Sign In or Register to comment.