[英]how to create a one parameter constructor that calls a three parameter constructer
create a one parameter constructor that initializes the year variable while setting the day and month variables to 1. This constructor MUST call the three- parameter constructor .创建一个单参数构造函数,在将日和月变量设置为 1 的同时初始化 year 变量。此构造函数必须调用三参数构造函数。
//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");
}
Your date class is worse than the existing stuff.你的约会课比现有的东西更糟糕。 You should be using java.time
package.您应该使用java.time
包。
But if you must:但如果你必须:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.