我正在构建一个Date类,当我尝试使用它创建一个对象时,它不起作用。 (daysPerMonth中的错误) 但是,当我在对象之外使用setNewDay方法时,它确实有效。
你们有什么关于我做错的线索吗?
这是我的代码:
public class Date{
private Dag day;
private Maand month;
private Jaar year;
private int maxday;
public Date(int day, int month, int year){
setDate(day, month, year);
}
public void setDate(int day, int month, int year){
this.month = new Maand(month);
setNewDay(day);
this.year = new Jaar(year);
}
private void daysPerMonth(){
int february;
if(year.getYear()%4 == 0) {
february = 29;
}else{
february = 28;
};
int[] daymonth={31,february,31,30,31,30,31,30,31,30,31,30};
maxday = daymonth[month.getMonth() -1];
}
public void setNewDay(int day){
daysPerMonth();
if(day > 0 && day <= maxday){
this.day = new Dag(day);
} else {
System.out.println("Wrong day");
}
}
}
答案 0 :(得分:1)
我按初始化顺序看到了一个问题:
public void setDate(int day, int month, int year){
this.month = new Maand(month);
setNewDay(day); // this method depends indirectly on this.year, which is not yet
// initialized (setNewDay calls daysPerMonth which calls
// year.getYear())
this.year = new Jaar(year);
}
将其更改为:
public void setDate(int day, int month, int year){
this.year = new Jaar(year);
this.month = new Maand(month);
setNewDay(day);
}
答案 1 :(得分:1)
查看通话顺序,
public void setDate(int day, int month, int year){
this.month = new Maand(month);
setNewDay(day);
this.year = new Jaar(year);
}
应该是
public void setDate(int day, int month, int year){
this.month = new Maand(month);
this.year = new Jaar(year);
setNewDay(day);
}
由于setNewDay()
调用daysPerMonth()
并且需要年份(Jaar
)。
答案 2 :(得分:0)
取决于你尝试的年份。 从记忆中你需要三个条件来使二月正确:Isnot mod 100&amp;是mod 400
答案 3 :(得分:0)
由于您在初始化年份之前调用setNewDay()
方法(由默认为空)。
而setNewDay()
方法则调用{{ 1}}使用年份但是年份的方法当前为空(默认为每个引用的值)您将获得 NullPointerException
因此,您只需要在调用方法daysPerMonth()
之前初始化年份:
setNewDay()
因此,当您拨打 public void setDate(int day, int month, int year){
this.month = new Maand(month);
this.year = new Jaar(year);
setNewDay(day); //call this method after setting up the year
}
方法时,您的年份包含有效数据:
daysPerMonth()