0

I am attempting to create it so the user will type in a keyword and it will execute that case. This works fine, but I would like the user to also be able to write after the keyword and it will still find the correct case. For example, the user might input "SEARCH dogs and cats" and it would run the "SEARCH" case.

I attempted to do have a temporary variable that stored only the "SEARCH" portion of the string, but I received an error that it had to be a constant in the switch statements. Is there a workaround or will I have to use if else statements?

Here is some test code with the error:

switch(textField.getText)
{
   case SEARCH: case textField.getText().split(" ", 2)[0]:  // Error is occuring on the second case statement 
   // Statements
   break;

   case Default:
   lblOutput.setText("ERROR: NOT FOUND");
}
gobigred5
  • 1
  • 1
  • @RealSkeptic I think it is. It's a compile-time error ("it had to be a constant in the switch statements"). – ryanyuyu Apr 01 '15 at 20:51
  • @RealSkeptic updated original post – gobigred5 Apr 01 '15 at 20:54
  • 1
    Case names are resolved at compile-time. Which is why they have to be constant values. – Powerlord Apr 01 '15 at 20:54
  • 1
    So short answer is: there is no workaround for the case statement for runtime "constants". If-else will work fine. – ryanyuyu Apr 01 '15 at 20:55
  • The `case` labels are what you want to compare your data *to*, not your actual data. `textField.getText().split(" ", 2)["0"]` is your *data*. Therefore it cannot be a `case`. – RealSkeptic Apr 01 '15 at 20:57
  • possible duplicate of [Java switch statement: Constant expression required, but it IS constant](http://stackoverflow.com/questions/3827393/java-switch-statement-constant-expression-required-but-it-is-constant) – DNA Apr 01 '15 at 20:59

1 Answers1

0

You need to specify one of three things in a case statement:

  1. A constant
  2. An Enum
  3. Default keyword

Refer to https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11

In addition, you have a "case" within a "case" with no intermediate "switch" statement.

jhenderson2099
  • 956
  • 8
  • 17
  • 1
    Two consecutive `case` labels are actually quite legal. It's just that neither of them can be a non-constant expression. – RealSkeptic Apr 01 '15 at 21:07
  • That's true. I forgot about that. (i.e. if you have several conditions that use the same logic). I wasn't interpreting the original post in that manner, but it is legal. – jhenderson2099 Apr 01 '15 at 21:14