javaswitch-statementprogram-flow

How to consolidate cases in a switch statement?


In a program I am currently working on, I am utilizing a switch statement with many cases yielding the same result. The relevant bit of my current code looks like this:

int[] vinArray = new int[17];
    for(int x=0;x<17;x++)
    {
        v = vinString.substring(x,x+1);

        switch(v)
        {
            case "A": vinArray[x]=1; break;
            case "B": vinArray[x]=1; break;
            case "C": vinArray[x]=1; break;
            case "D": vinArray[x]=1; break;
            case "E": vinArray[x]=1; break;
            case "F": vinArray[x]=1; break;
            case "G": vinArray[x]=1; break;
            case "H": vinArray[x]=1; break;
            case "J": vinArray[x]=2; break;
            case "K": vinArray[x]=2; break;
            case "L": vinArray[x]=2; break;
            case "M": vinArray[x]=2; break;
            case "N": vinArray[x]=2; break;

        }
}

I was wondering if their is a way to consolidate the cases that perform the action is a manner like this (psuedo-code):

case "A", "B", "C", "D", "E", "F", "G", "H": vinArray[x]=1; break;

Solution

  • Simply omit the break between cases to fall through:

    case "A":
    case "B":
    case "C": // etc
      vinArray[x] = 1;
      break;
    case "J":
    case "K": // etc
      vinArray[x] = 2;
      break;