mardi 6 février 2018

Advance a Date in Java (including leap years and year changes.)

So I have to complete a MyDate class, and the requirements are to advance the date, without using any imports/etc. The code that I have now is a start to what I have, and I have already included the leap year portion, but need the section that adds a day, or when the day reaches say 31, add a month and bring the day back to 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);
        }


     }
  }

These are two test cases given in order to check if the date increases.

    //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");            
    }

Any answer would be nice, I am new to this and will try to answer any questions you may have.

Aucun commentaire:

Enregistrer un commentaire