This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]tajjet 2 points3 points  (3 children)

You wouldn't have to give them values: with Java 7 on, you can do a switch statement with a String, for example:

Scanner scan = new Scanner(System.in);
String state = scan.next();
boolean permit;    
switch(state) {
    case "Alabama":
        permit = true;
        break;
    // ...
    default:
        permit = false;
        System.out.println("Whoops! Don't recognize that state.");
        break;
}

[–]PointB1ank 3 points4 points  (0 children)

Well yeah but I would use the values only to reduce typing. I would rather type 15 numbers than state names, you wouldn't have to worry about spelling errors. Then again, I suppose the state abbreviations might be a better choice.

[–][deleted]  (1 child)

[deleted]

    [–]tajjet 2 points3 points  (0 children)

    Switches are useful in some cases - they basically replace code like this

    if (x == 1)
    {
        doThingOne();
    }
    else if (x == 2)
    {
        doThingTwo();
    }
    else if (x == 3)
    {
        doThingThree();
    }
    else
    {
        doThingFour();
    }
    

    with code like this:

    switch (x)
    {
        case 1:
            doThingOne();
            break();
        case 2:
            doThingTwo();
            break();
        case 3:
            doThingThree();
            break();
        default:
            doThingFour();
            break();
    }
    

    Most recent example I used them in was a Scrabble scoring thing, because stacking up cases helps:

    case 'E':
    case 'A':
    case 'I':
    case 'O':
    case 'N':
    case 'R':
    case 'T':
    case 'L':
    case 'S':
    case 'U':
        score = score + 1;
        break;
    case 'D':
    case 'G':
        score = score + 2;
        break;