4 ms·
You can now finally use a string in a switch statement, hurray (it's the little things that make me happy)! http://download.oracle.com/javase/7/docs/technotes/
by j_col 15y ago
You can now finally use a string in a switch statement, hurray (it's the little things that make me happy)!
http://download.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html http://download.oracle.com/javase/7/docs/technotes/guides/la...
- st3fan 15y agoIntelliJ IDEA strongly suggests to turn those Strings into constants. And then to turn those constants into an Enum. Oh wait, we could also switch() on Enum values! I'm sure this is useful in some cases though :-)
- dxbydt 15y agoGod, I seriously hope string-switching doesn't catch on. In a prev job, I saw this block of code - ------- public int getDaysInMonth( String month ) { if( month.equalsIgnoreCase("january")) return 31; else if( month.equalsIgnoreCase("february")) return 28; else if( month.equalsIgnoreCase("march")) return 31; else if( month.equalsIgnoreCase("april")) return 30; ... } ------- My eyes bled. I said folks, just map the month to an int M in range [1..12] and simply write 1 line of code return 30+((M+Math.floor(M/8))%2; ( except for 2, which is 28 or 29 depending on a leap year) I was overruled. "We are programmers, not mathematicians" was the response!!! Now they'll happily use this string-switch to do --------- switch( month.toLowerCase() ) { case "january" return 31; case "february" return 28; case "march" return 31; case "april" return 30; ... default : return -1; } ------- which is an even nastier abomination :(
- chubot 15y agoAre you serious? An "abomination"? The switch statement is fine, and using an array [31, 30, 31 ...] would be fine as well. Your 1 line isn't really 1 line because you have to convert the month to an integer anyway, and then the array lookup is even shorter than your solution.
- VMG 15y agoYour one-liner is more difficult to understand. The string switch is very explicit and understandable.
- bethling 15y agoI have to admit - I never even thought that there would be an easier math-formula way to calculate it. Though I would have written the switch: case "september": case "april": case "june": case "november": return 30; It's sad, but still need to go through the poem in my head to remember most of the time.
- oleeang 15y agoUse the knuckles trick: http://lifehacker.com/232828/macgyver-tip-use-your-knuckles-to-remember-each-months-days http://lifehacker.com/232828/macgyver-tip-use-your-knuckles-...
- Bootvis 15y agoTo be honest your one liner takes me a while to parse and you forgot to close a parenthesis. OTOH It is really hard to read or write that switch incorrectly.
- kragen 15y agoI have to say, I think it's easier to verify the correctness of [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][M-1] than your formula. Even a dictionary wouldn't be bad. And if it were wrong, it would be easier to fix it.
- fleitz 15y ago