我知道我可以通过使用Guava中的Preconditions类或通过提取方法isValidDayOfWeek()
来即兴发挥这一点(消除显式抛出)。但这不是我想要的。有没有办法在不使用switch语句的情况下简化此逻辑?此检查确保startDayOfWeek
是本周7个值中的一个。
public static TimeSlice getPreviousWeek(Date referenceDate, int startDayOfWeek)
{
if (!((startDayOfWeek == Calendar.SUNDAY) || (startDayOfWeek == Calendar.MONDAY) || (startDayOfWeek == Calendar.TUESDAY)
|| (startDayOfWeek == Calendar.WEDNESDAY) || (startDayOfWeek == Calendar.THURSDAY)
|| (startDayOfWeek == Calendar.FRIDAY) || (startDayOfWeek == Calendar.SATURDAY)))
{
throw new IllegalArgumentException("getPreviousWeek(): invalid startDayOfWeek:" + startDayOfWeek);
}
}
答案 0 :(得分:3)
保证一周中某些天的值documented,SUNDAY == 1和SATURDAY == 7所以你只想要:
if (startDayOfWeek < Calendar.SUNDAY || startDayOfWeek > Calendar.SATURDAY)
{
throw ...;
}
如果你想让它清晰透明,你可以随时使用:
private static final Set<Integer> VALID_DAYS = ImmutableSet.of(
Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY,
Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY,
Calendar.SATURDAY);
public static TimeSlice getPreviousWeek(Date referenceDate, int startDayOfWeek)
{
if (!VALID_DAYS.contains(startDayOfWeek))
{
throw ...
}
}
(那是使用Guava的ImmutableSet
,但如果你愿意,可以使用别的东西。)
答案 1 :(得分:1)
你可以这样做:
if ((startDayOfWeek < Calendar.SUNDAY) || (startDayOfWeek > Calendar.SATURDAY))