22

How can I convert the following code to switch statement?

String x = "user input";

if (x.contains("A")) {
    //condition A;
} else if (x.contains("B")) {
    //condition B;
} else if(x.contains("C")) {
    //condition C;
} else {
    //condition D;
}
assylias
  • 321,522
  • 82
  • 660
  • 783
Kiddo
  • 5,052
  • 6
  • 47
  • 69

7 Answers7

20

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;
  }
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • 1
    works only if the conditions are limited to **"[ABCD]"**, wont work if I want to check for a random letter or word – Sangeet Menon Jul 19 '12 at 09:56
  • 1
    No exactly readable and intuitive, but it does the job! It could be abstracted away to commented method with a good descriptive name, then it would be just nice. – Petr Janeček Jul 19 '12 at 09:56
  • 3
    @Slanec Intuitiveness is totally in the eye of the beholder. To a non-programmer, no line of code in any programming language is intuitive. To someone who codes everyday with regex's, this is a direct and obvious solution. – Marko Topolnik Jul 19 '12 at 10:00
  • good one. just like Sangeet mentioned, if i wanna do longer words or sentences, it might need some improvements, but still – Kiddo Jul 19 '12 at 15:42
  • 1
    Kiddo, in Java 7 you are covered for longer strings, the regex syntax is only sligthly different. – Marko Topolnik Jul 19 '12 at 17:38
  • The problem i am seeing with this is that in the original question is creating a scenario where you are searching for multiple constant strings within 1 variable. As Sangeet mentioned in this solution it only allows you to do 1 type of search – hfrog713 Feb 08 '17 at 14:01
  • @hfrog713 Not sure I follow you... but you can use this technique to search for any set of strings you choose. `Pattern.compile("search|for|any|of|these")` and `switch (m.group()) { case "search": case "for": ...)` – Marko Topolnik Feb 08 '17 at 14:48
  • 1
    `Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.` Jamie Zawinski – tostao Jun 17 '20 at 05:58
8

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

5

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...
}
Anurag Upadhyaya
  • 301
  • 2
  • 6
  • 17
4
@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
Jatin Singla
  • 293
  • 4
  • 12
3

No you cannot use the switch with conditions

The JAVA 7 allows String to be used with switch case

Why can't I switch on a String?

But conditions cannot be used with switch

Community
  • 1
  • 1
Sangeet Menon
  • 9,555
  • 8
  • 40
  • 58
2

you can only compare the whole word in switch. For your scenario it is better to use if

SMK
  • 2,098
  • 2
  • 13
  • 21
1

also HashMap:

String SomeString = "gtgtdddgtgtg";

Map<String, Integer> items = new HashMap<>();
items.put("aaa", 0);
items.put("bbb", 1);
items.put("ccc", 2);
items.put("ddd", 2);

for (Map.Entry<String, Integer> item : items.entrySet()) {
    if (SomeString.contains(item.getKey())) {
        switch (item.getValue()) {
            case 0:
                System.out.println("do aaa");
                break;
            case 1:
                System.out.println("do bbb");
                break;
            case 2:
                System.out.println("do ccc&ddd");
                break;
        }
        break;
    }
}
Matt Ke
  • 3,599
  • 12
  • 30
  • 49
semerkin
  • 11
  • 1