使用 Java 根据迭代从字符串数组中查找日期
Find day from String array based on iteration using Java
我的字符串数组和输入如下
S = "Tue" and K = 23
String[] daysOfWeek = {"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
我输入“星期二”并在 10 天后查找第二天。我期待答案为“星期五”
这是我的代码
String[] daysOfWeek = {"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
int day = Arrays.asList(daysOfWeek).indexOf(S);
int n = K % 7;
if((day + n) > 6) {
int index = (day + n) % 6;
//return daysOfWeek[ ];
} else {
return daysOfWeek[day + n ];
}
return null;
任何想法
你可以对之后的天数进行模7,然后你可以根据输出找到将索引从起始位置移动到结果。
您可以使用java.time.DayOfWeek
而不是重新发明轮子。
例如:
DayOfWeek dayOfWeek = DayOfWeek.TUESDAY;
DayOfWeek dayOfWeek1 = dayOfWeek.plus(10);
System.out.println(dayOfWeek1); // FRIDAY
混合方法 -
String[] daysOfWeek = {"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
int today = LocalDate.now().getDayOfWeek().getValue()-1;
for (int i = 0; i < 31; i++) {
System.out.println(daysOfWeek[today] + " >>> " + i + " - " + daysOfWeek[(today+i)%7]);
}
简单一点!
private static final String[] DAYS_OF_WEEK = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
private static final Map<String, Integer> MAP = Map.of(DAYS_OF_WEEK[0], 0, DAYS_OF_WEEK[1], 1,
DAYS_OF_WEEK[2], 2, DAYS_OF_WEEK[3], 3, DAYS_OF_WEEK[4], 4, DAYS_OF_WEEK[5], 5, DAYS_OF_WEEK[6], 6);
public static String find(String dayOfWeek, int days) {
return DAYS_OF_WEEK[(MAP.get(dayOfWeek) + days) % 7]; // NPE if not found
}
我的字符串数组和输入如下
S = "Tue" and K = 23
String[] daysOfWeek = {"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
我输入“星期二”并在 10 天后查找第二天。我期待答案为“星期五”
这是我的代码
String[] daysOfWeek = {"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
int day = Arrays.asList(daysOfWeek).indexOf(S);
int n = K % 7;
if((day + n) > 6) {
int index = (day + n) % 6;
//return daysOfWeek[ ];
} else {
return daysOfWeek[day + n ];
}
return null;
任何想法
你可以对之后的天数进行模7,然后你可以根据输出找到将索引从起始位置移动到结果。
您可以使用java.time.DayOfWeek
而不是重新发明轮子。
例如:
DayOfWeek dayOfWeek = DayOfWeek.TUESDAY;
DayOfWeek dayOfWeek1 = dayOfWeek.plus(10);
System.out.println(dayOfWeek1); // FRIDAY
混合方法 -
String[] daysOfWeek = {"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
int today = LocalDate.now().getDayOfWeek().getValue()-1;
for (int i = 0; i < 31; i++) {
System.out.println(daysOfWeek[today] + " >>> " + i + " - " + daysOfWeek[(today+i)%7]);
}
简单一点!
private static final String[] DAYS_OF_WEEK = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
private static final Map<String, Integer> MAP = Map.of(DAYS_OF_WEEK[0], 0, DAYS_OF_WEEK[1], 1,
DAYS_OF_WEEK[2], 2, DAYS_OF_WEEK[3], 3, DAYS_OF_WEEK[4], 4, DAYS_OF_WEEK[5], 5, DAYS_OF_WEEK[6], 6);
public static String find(String dayOfWeek, int days) {
return DAYS_OF_WEEK[(MAP.get(dayOfWeek) + days) % 7]; // NPE if not found
}