java string.contains in switch statement

You can't switch on conditions like x.contains(). Java 7 supports switch on Strings but not like you want it. Use if etc.


@Test
public void test_try() {
    String x = "userInputA"; // -- test for condition A
    String[] keys = {"A", "B", "C", "D"};
    String[] values = {"conditionA", "conditionB", "conditionC", "conditionD"};

    String match = "default";
    for (int i = 0; i < keys.length; i++) {
        if (x.contains(keys[i])) {
            match = values[i];
            break;
        }
    }

    switch (match) {
        case "conditionA":
            System.out.println("some code for A");
            break;
        case "conditionB":
            System.out.println("some code for B");
            break;
        case "conditionC":
            System.out.println("some code for C");
            break;
        case "conditionD":
            System.out.println("some code for D");
            break;
        default:
            System.out.println("some code for default");
    }
}

Output:

some code for A

There is a way, but not using contains. You need a regex.

final Matcher m = Pattern.compile("[ABCD]").matcher("aoeuaAaoe");
if (m.find())
  switch (m.group().charAt(0)) {
  case 'A': break;
  case 'B': break;
  }

Condition matching is not allowed in java in switch statements.

What you can do here is create an enum of your string literals, and using that enum create a helper function which returns the matched enum literal. Using that value of enum returned, you can easily apply switch case.

For example:

public enum Tags{
   A("a"),
   B("b"),
   C("c"),
   D("d");

   private String tag;

   private Tags(String tag)
   {
      this.tag=tag;
   }

   public String getTag(){
      return this.tag;
   }

   public static Tags ifContains(String line){
       for(Tags enumValue:values()){
         if(line.contains(enumValue)){
           return enumValue;
         }
       }
       return null;
   }

}

And inside your java matching class,do something like:

Tags matchedValue=Tags.ifContains("A");
if(matchedValue!=null){
    switch(matchedValue){
       case A:
         break;
       etc...
}