0

Given this code it will print out the correct month and year but seems to display random days that are usually incorrect. I have looked over some links including here and here

import java.util.Calendar;
import javax.swing.JOptionPane;
public class DayOfTheWeek {
  Calendar now = Calendar.getInstance();
  int month;
  int year;
  String[] monthString;
  public String monthOfInspection() {
    String Month = JOptionPane.showInputDialog("Select month of inspection: ");
    month = Integer.parseInt(Month);
    monthString = new String[] {
      "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"
    };
    return monthString[month - 1];
  }
  public int yearOfInspection() {
    if(month == 1) {
      now.get(Calendar.YEAR);
      now.add(Calendar.YEAR, 1);
    }
    year = now.get(Calendar.YEAR);
    return year;
  }
  public void dayOfTheWeek() {
    now.set(Calendar.DAY_OF_MONTH, 1);
    now.set(Calendar.MONTH, month);
    now.set(Calendar.YEAR, year);
    now.set(Calendar.DAY_OF_WEEK_IN_MONTH, 0);
    String[] strDays = new String[] {
      "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    };
    JOptionPane.showMessageDialog(null, year);
    JOptionPane.showMessageDialog(null, monthString[month - 1]);
    JOptionPane.showMessageDialog(null, now.get(Calendar.DAY_OF_WEEK_IN_MONTH));
    JOptionPane.showMessageDialog(null, strDays[now.get(Calendar.DAY_OF_WEEK_IN_MONTH) - 1]);
  }
}
Community
  • 1
  • 1
user2155373
  • 1
  • 1
  • 1

2 Answers2

0

You probably should use Calendar.DAY_OF_WEEK instead of Calendar.DAY_OF_WEEK_IN_MONTH.

public void dayOfTheWeek() {
    now.set(Calendar.YEAR, year);
    now.set(Calendar.MONTH, month);
    now.set(Calendar.DAY_OF_MONTH, 1);

    String[] strDays = new String[] {
      "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    };
    JOptionPane.showMessageDialog(null, year);
    JOptionPane.showMessageDialog(null, monthString[month - 1]);
    JOptionPane.showMessageDialog(null, now.get(Calendar.DAY_OF_WEEK));
    JOptionPane.showMessageDialog(null, strDays[now.get(Calendar.DAY_OF_WEEK) -     1]);
  }
mixel
  • 25,177
  • 13
  • 126
  • 165
0

Assuming you have correct month and year this is what you can do:

now.set(Calendar.DATE, 1);
now.set(Calendar.MONTH, month);
now.set(Calendar.YEAR, year);
int dayOfWeek = now.get(Calendar.DAY_OF_WEEK);