Input would be month day year
, and output the day of week.
//sample input
08 05 2015
//sample output
WEDNESDAY
proper solution
DISCLAIMER: the solution referenced from the editorial
public static String findDay(int year, int month, int day) {
Calendar date = Calendar.getInstance();
date.set(year, month, day);
return date.get(Calendar.DAY_OF_WEEK); //error
}
The code would have error because date.get(Calendar.DAY_OF_WEEK)
returns integer value of day of week. For example, returns 1 for SUNDAY, 2 for MONDAY, and 7 for SATURDAY.
We need to create an additional array to reference day of week:
// outside main method
static String[] dayOfWeek = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
public static String findDay(int year, int month, int day) {
Calendar date = Calendar.getInstance();
date.set(year, month, day);
return dayOfWeek[date.get(Calendar.DAY_OF_WEEK)-1];
}
use another class
Instead of the class java.util.Calendar
it mentioned, java.time.LocalDate
(Java 8 and higher) actually finish all the work nice and neat.
public static String findDay(int year, int month, int day) {
LocalDate date = LocalDate.of(year, month, day);
return date.getDayOfWeek().toString(); //getDayOfWeek() returns a DayOfWeek object
}
Top comments (0)