hashCode
of the String and then performing an equals test.
Here is an example of a method which returns the number of days in a month. It uses if-else statements and string equality:
public static int getDaysInMonth(String month, int year) { if("January".equals(month) || "March".equals(month) || "May".equals(month) || "July".equals(month) || "August".equals(month) || "October".equals(month) || "December".equals(month)) return 31; else if("April".equals(month) || "June".equals(month) || "September".equals(month)|| "November".equals(month)) return 30; else if("February".equals(month)) return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29 : 28; else throw new IllegalArgumentException("Invalid month: " + month); }The same code can be rewritten neatly using strings-in-switch as follows:
public static int getDaysInMonth2(String month, int year) { switch(month) { case "January": case "March": case "May": case "July": case "August": case "October": case "December": return 31; case "April": case "June": case "September": case "November": return 30; case "February": return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29 : 28; default: throw new IllegalArgumentException("Invalid month: " + month); } }Further Reading:
Strings in switch Statements
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.