Switch!

Nov 22, 2008 15:47

Hi

So the switch statements in Java... I don't know, people! Check this out:

Switch (category) {
case ONES : family(dice, category);
case TWOS : family(dice, category);
case THREES : family(dice, category);
case FOURS : family(dice, category);
case FIVES : family(dice, category);
case SIXES : family(dice, category);
case THREE_OF_A_KIND : ofAKind(dice, 3);
case FOUR_OF_A_KIND : ofAKind(dice, 4);
case YAHTZEE : ofAKind(dice, 5);
}

OK so I would pass in dice and category, and then it would give me back a correct score for those dice... until I added those ofAKind guys, and then it would just always give me 0! I took them out, and I put them back in... and again: nothing!

So it turns out that you need to insert break; at the end of each line, or else it will just iterate over every case every time. Since my original six cases are essentially identical, just passing different numbers to the same function, it would still give me the correct answer each time. Once I added the ofAKind guys it would be replacing the correct score with 0s.

Doesn't that seem counter-intuitive? I mean, isn't the whole point of a switch-statement to execute different code in each case? Should each case imply a break at the end of the line? It didn't take me long to figure out the problem, but still it strikes me as sort of useless. I mean, I really might be better-off using a bunch of ELSE IF statements...

Ruby, now she'd never treat me wrong like that:

case category
when ONES, TWOS, THREES, FOURS, FIVES, SIXES then family(dice, category)
when THREE_OF_A_KIND then ofAKind(dice, 3)
when FOUR_OF_A_KIND then ofAKind(dice, 4)
when YAHTZEE then ofAKind(dice, 5)
end

oh man? Writing that little paragraph reminded me: I love RUBY! When I write in Ruby I always feel like naming my variables and constants names that make for easy reading. Like
when ITS_YATZEE then matching(dice, 3) isn't that lovely? Much nicer, anyway, than blunt old bean machine java with it's
case ITS_YAHTZEE : matching(dice, 3); break; I feel like he's just yelling at me... BREAK!!!; I've been studying C on the side... it's not as friendly as Java either (it seems so high-society, with it's snooty ampersands).

OK I'm done.

z.
Previous post Next post
Up