Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java switch statement to handle two variables?

I'm looking for a way to handle two strings using a single switch, I'm thinking this impossible within Java.

Here is some pseudo code of the kind of thing I want to achieve with a switch only.

    int s1Value = 0;
    int s2Value = 0;
    String s1 = "a";
    String s2 = "g";
    switch (s1 || s2) {
         case "a": s1value = 0; s2value = 0; break;
         case "b": s1value = 1; s2value = 1; break;
         case "c": s1value = 2; s2value = 2; break;
         case "d": s1value = 3; s2value = 3; break;
         case "e": s1value = 4; s2value = 4; break;
         case "f": s1value = 5; s2value = 5; break;
         case "g": s1value = 6; s2value = 6; break;
    }
like image 932
Ciphor Avatar asked Mar 05 '13 11:03

Ciphor


3 Answers

Languages like scala&python give to you very powerful stuff like patternMatching, unfortunately this is still a missing-feature in Java...

but there is a solution (which I don't like in most of the cases), you can do something like this:

final int s1Value = 0;
final int s2Value = 0;
final String s1 = "a";
final String s2 = "g";

switch (s1 + s2 + s1Value + s2Value){
    case "ag00": return true;
    default: return false;
}
like image 119
Andrea Ciccotta Avatar answered Oct 06 '22 18:10

Andrea Ciccotta


Have you considered not using the switch statement but instead using lookup tables?

public class MyClass {
    private static final Map<String, Integer> valuesMap;

    static {
         Map<String,Integer> aMap = new HashMap<>();
         aMap.put("a", 0);
         aMap.put("b", 1);
              ..... rest .....
         valuesMap = Collections.unmodifiableMap(aMap);
    }

    public void foo()
    {
       int s1Value = 0;
       int s2Value = 0;

       String s1 = "a";
       String s2 = "g";
       if( valuesMap.containsKey(s1) )
       {
          s1Value = valuesMap.get(s1);
          s2Value = s1Value;
       }
       else if( valuesMap.contansKey(s2) )
       {
          s1Value = valuesMap(s2);
          s2Value = s1Value;
       }
    }
}

If you needed a different set of values of the s2Value then you could construct a second map to pull those from.

Since you wanted to use a switch I take that to mean the possible candidates and values is a fixed, known at development time list, so using a statically initialized map like this shouldn't be an issue.

like image 32
Jere Avatar answered Oct 06 '22 19:10

Jere


Using a single switch per your requirement is not possible. This is as close as your going to get using Java.

    switch (s1)  {
        case "a":  doAC(); break;
        case "b":  doBD(); break;
        default:
            switch(s2) {
                case "c":  doAC(); break;
                case "d":  doBD(); break;
            }
   }        
like image 37
Java42 Avatar answered Oct 06 '22 18:10

Java42