Reputation: 2607
I have my string array and the input as follows
S = "Tue" and K = 23
String[] daysOfWeek = {"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
I give my input as "Tue" and to find the next day after 10 days. I'm expecting answer as "Fri"
Here is my code
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;
Any ideas
Upvotes: 0
Views: 242
Reputation: 28289
You can use java.time.DayOfWeek
instead of reinventing the wheel.
For example:
DayOfWeek dayOfWeek = DayOfWeek.TUESDAY;
DayOfWeek dayOfWeek1 = dayOfWeek.plus(10);
System.out.println(dayOfWeek1); // FRIDAY
Upvotes: 4
Reputation: 18255
Be simple!
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
}
Upvotes: 1
Reputation: 2438
a mixed approach -
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]);
}
Upvotes: 0
Reputation: 152
You can do modulo 7 for the number of days after, and then you can find based on the output move the index to the result from the starting position.
Upvotes: 0