用Java推进日期(包括闰年和年度变化。)

时间:2018-02-06 19:56:55

标签: java class object testing

所以我必须完成一个MyDate类,并且要求是推进日期,而不使用任何导入/等。我现在拥有的代码是我拥有的代码,我已经包含了闰年部分,但需要添加一天的部分,或者当一天达到31时,添加一个月并将一天带回0

  private int year;
  private int month;
  private int day;

  //Constructors (1) and (2)
  public MyDate(int d, int m, int y){
      this.year = y;
      this.month = m;
      this.day = d;
  }

  public MyDate(int y){
      this(1, 1, y);
  }

  //Accessors for the three instance variables
  public int getYear(){
       return year;
  }
  public int getMonth(){
       return month;
  }
  public int getDay(){
       return day;
  }

  //The advance method as stubbed out below
  public void advance(){
       MyDate test = new MyDate(day, month, year);

     if(day <= 31 && day >= 1){
        test = new MyDate(day += 1, month, year);

        if(day > 28 && month == 2 && year % 4 != 0){
            test = new MyDate(day -= 28, month += 1, year);
        }


     }
  }

这是为了检查日期是否增加而给出的两个测试用例。

    //TC 1 : 1/31/2013 advances to 02/01/2013
    date = new MyDate(31,1,2013);
    date.advance();
    correctDate = new MyDate(1,2,2013);
    if(date.equals(correctDate)){
        System.out.println("TC 3 passed");
    }else{
        System.out.println("TC 3 failed");                
    }

    //TC 2 : 02/28/2013 advances to 03/01/2013
    date = new MyDate(28,2,2013);
    date.advance();
    correctDate = new MyDate(1,3,2013);
    if(date.equals(correctDate)){
        System.out.println("TC 4 passed");
    }else{
        System.out.println("TC 4 failed");            
    }

任何答案都会很好,我是新手,会尝试回答你的任何问题。

1 个答案:

答案 0 :(得分:0)

正如Jon Skeet所提到的,您应首先创建一个返回特定月份天数的方法。例如,如果您要求5月份的天数,它将返回31;如果您要求2月份的天数,它将返回28/29,具体取决于该月是否为闰年。

该方法可以像拥有大量if-else-if语句一样简单。

e.g。

getDaysForMonth() {
  if (month == 1) { // January
    return 31;
  }
  else if (month == 2) { // February
    // special case, will have to do some more complex checks here :)
    // you may already have these conditions in your question body
    if (/* year is a leap year */) {
      return 29;
    }
    else {
      return 28;
    }
  }
  // and so on ...
}

使用上述方法,您只需通过advance()方法调用它,并检查是否需要增加日期或重置为1:

advance() {
  int lastDayThisMonth = getDaysForMonth();

  if (day == lastDayThisMonth) {
    // reset day to 1
    // increase month (also have to know whether it's the last month and reset it accordingly)
    // (hint: modulo operator % is your friend)
    // possibly increase year (if month gets reset to 1 too)
  }
  else {
    // increment day
  }
}

我省略了一些数据类型声明,并将一些语句作为注释写出来,以便您自己编写代码。我想你会得到全面的想法。

注意:上面的结构应该改变原始对象。如果您正在寻找一个不可变版本,您应该返回一个新的MyDate对象,如Jon Skeet所提到的那样。

相关问题