如何创建一个调用三个参数约束器的一个参数构造函数



创建一个初始化的参数构造函数年 多变的设置天和月变量到1。该构造函数必须称为三个范围构造函数。

 //constructor one
 public MyDate(int year){
  // this is what I have so far for the first constructor but it doesnt seem to be correct.
   this.day = 1;
   this.month = 1;
 // call for the three parameter constructor .
   MyDate myDate = new MyDate ( day=1 , month=1, year);
  }
  // constructor two
  public MyDate(int day, int month, int year){
  ........
  }

  public static void main(String[] args){   
    //Check whether a user input advances correctly
    java.util.Scanner scan = new java.util.Scanner(System.in);
    System.out.println("Enter a date to advance, in format day month year: ");
    int year,month,day;       
    day = scan.nextInt();
    month = scan.nextInt();
    year = scan.nextInt();
    MyDate date = new MyDate(day, month, year);
    System.out.println("Entered date is "+ date);

    MyDate correctDate;
    //TC 1 : one parameter constructor. 
    // not passing this test
    date = new MyDate(2013);
    correctDate = new MyDate(1,1,2013);
    if (date.equals(correctDate))
        System.out.println("TC 1 passed");
    else
        System.out.println("TC 1 failed");  
   }

您的日期类比现有内容差。您应该使用java.time软件包。

,但如果您必须:

public class MyDate {
    private final int year;
    private final int month;
    private final int day;
    public MyDate(int y) {
        this(y, 1, 1);
    }
    public MyDate(int y, int m, ind d) {
        this.year = y;
        this.month = m;
        this.day = d;
    }
}

最新更新