0

Can any1 tell me what's wrong with my code? I'm getting an incorrect output. Cheers

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String[] days={"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
    int month = in.nextInt();
    int day = in.nextInt();
    int year = in.nextInt();
    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR,  year);
    c.set(Calendar.MONTH,  month);
    c.set(Calendar.DAY_OF_MONTH,  day);
    int day_of_week = c.get(Calendar.DAY_OF_WEEK)-1;
    System.out.println(days[day_of_week]);
}
Vlad Stan
  • 13
  • 1
  • 1
    what is the output and what is expected ? – Ravi Jul 03 '17 at 07:09
  • 1
    "I'm getting an incorrect output" - without knowing the input, expected output or actual output, it's quite difficult to help. My guess is that you aren't using 0-based months. Note that if you can possibly use `java.time` or the threeten backport, that's likely to cause fewer problems than `java.util.Calendar`. – Jon Skeet Jul 03 '17 at 07:09
  • Possible duplicate of [How to determine day of week by passing specific date?](https://stackoverflow.com/questions/5270272/how-to-determine-day-of-week-by-passing-specific-date) – Chris Jul 03 '17 at 07:10
  • I cannot more strongly advise against using the legacy `java.util.Calendar` class. You should instead look at the `java.time` package for the class that is most appropriate for your use case (which in your case is probably `LocalDate`). – Joe C Jul 03 '17 at 07:10
  • You can use `set(int year, int month, int date)` too. – Marco Luzzara Jul 03 '17 at 07:16

1 Answers1

5

Read the docs and then change to

c.set(Calendar.MONTH,  month -1);

as it accepts a zero based index

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64