import java.util.regex.Pattern; import java.util.regex.Matcher; public class Interval { int startHour; int startMin; int endHour; int endMin; /** Given a matcher, return the next occurence, converted to an int value @param m A matcher of a regular expression on a string, where it is assumed that the string matched will be a valid integer. @param str The original string (used for error messages) */ public static int getNextInt(Matcher m, String str) { if (m.find()) { return Integer.parseInt(m.group()); } else { throw new IllegalArgumentException(str + "is not in the expected format"); } } /** @param str A string representing an interval such as "1:20pm - 2:30pm" */ public Interval(String str) { Matcher oneOrTwoDigitsMatcher = Pattern.compile("\\d{1,2}").matcher(str); Matcher amOrPmMatcher = Pattern.compile("[ap]m").matcher(str); // get the start hour---that's the first occurence of 1 or 2 digits this.startHour = getNextInt(oneOrTwoDigitsMatcher,str); this.startMin = getNextInt(oneOrTwoDigitsMatcher,str); this.endHour = getNextInt(oneOrTwoDigitsMatcher,str); this.endMin = getNextInt(oneOrTwoDigitsMatcher,str); if (amOrPmMatcher.find()) { if (amOrPmMatcher.group().equals("pm") && startHour != 12) { startHour += 12; } } else { throw new IllegalArgumentException(str + "is not in the expected format"); } if (amOrPmMatcher.find()) { if (amOrPmMatcher.group().equals("pm") && endHour != 12) { endHour += 12; } } else { throw new IllegalArgumentException(str + "is not in the expected format"); } } public int getStartHour() { return this.startHour;} public int getStartMin() { return this.startMin;} public int getEndHour() { return this.endHour;} public int getEndMin() { return this.endMin;} }