获取一周中的某一天,switch语句/ toString会发出闰年的实现

时间:2014-09-17 00:49:53

标签: java switch-statement tostring dayofweek

我正在为学校和我的小组成员开展一个小项目,我在代码中遇到了一些问题。我们需要编写用于确定星期几的代码,任何给定的日期都将打开,我们有代码,我们使用switch语句来帮助为方程输出分配正确的日期。例如,如果等式返回0,则为星期日,1为星期一,依此类推。

这是我们到目前为止所做的:

*/
public class Date {
  /**
   * Construct a date object.
   * @param year the year as integer, i.e. year 2010 is 2010.
   * @param month the month as integer, i.e. 
   *              january is 1, december is 12.
   * @param dayOfMonth the day number in the month, range 1..31.
   * PRECONDITION: The date parameters must represent a valid date.
  */
      private int year;
      private int month;
      private int dayOfMonth;

  public Date(int year, int month, int dayOfMonth) {
      this.year = year;
      this.month = month;
      this.dayOfMonth = dayOfMonth;
  }

  public enum Weekday { 
      MONDAY, TUESDAY, WEDNESDAY, 
      THURSDAY, FRIDAY, 
      SATURDAY, SUNDAY };

  public String toString() {
      String theDate = month + " " + dayOfMonth + ", " + year;
      return theDate;
  }

  public boolean isLeapYear(){
        if ((this.year % 400 == 0)|| (this.year % 100 != 0 && this.year % 4 == 0))
                return true;
        else return false;
  /**
  * Calculate the weekday that this Date object represents.
  * @return the weekday of this date.
  */
  public String dayOfWeek() {


  int century = year/100; 

      int day = (dayOfMonth - month +  year +(year/4) + century) %7;
      Weekday i;
      switch(day){
      case 1:
           i = Weekday.MONDAY;
           System.out.println("The day of the week for this month is Monday.");
      case 2:
           i = Weekday.TUESDAY;
           System.out.println("The day of the week for this month is Tuesday.");
      case 3:
           i = Weekday.WEDNESDAY;
           System.out.println("The day of the week for this month is Wednesday.");
      case 4:
           i = Weekday.THURSDAY;
           System.out.println("The day of the week for this month is Thursday.");
      case 5:
           i = Weekday.FRIDAY;
           System.out.println("The day of the week for this month is Friday.");
      case 6:
           i = Weekday.SATURDAY;
           System.out.println("The day of the week for this month is Saturday.");
      case 0:
           i = Weekday.SUNDAY;
           System.out.println("The day of the week for this month is Sunday.");
        }
return i.name();
  }
}

我们需要实现一个toString()方法,我们正在努力弄清楚dayOfWeek方法应该返回什么。另外,我们应该如何实施isLeapYear()方法?

1 个答案:

答案 0 :(得分:1)

在您遇到break;的情况下,如果匹配的case没有case,则Java会执行所有后续break;(直到找到下一个中​​断) 1}}。

您需要使用i初始化null至少(理想情况是使用后备日初始化,让我们说一周的第一天,以防它没有进入任何caseWeekDay i = null;WeekDay i = WeekDay.SUNDAY;

此外,您需要返回(完成switchi.name()之后。