我正在使用Junit / Java进行作业。此方法应转到正确的if语句,以通用日历的方式提前一天,然后退出整个方法。
我已经广泛搜索了这个问题。我找到的仅有的页面,指向我要执行的操作。我可能错过了一些东西,我只是不知道。当我通过调试器运行测试时,我看到Java确实执行了正确的语句,它只是“忽略”了返回值。
protected final void advanceDay() {
int[] highMonth = new int[]{1, 3, 5, 7, 8, 10, 12};
boolean isMonth31 = false;
for (int x : highMonth) {
if (this.monthFirstDay == x) {
isMonth31 = true;
}
}
//checks if month has 31 days
if (this.dayFristDay >= 30) {
if (this.dayFristDay == 31) {
this.dayFristDay = 1;
this.monthFirstDay++;
return;
}
//if it's the 31st, then proceed to the next month, the day is set to one.
if (this.dayFristDay == 31 && this.monthFirstDay == 12) {
this.dayFristDay = 1;
this.monthFirstDay = 1;
return;
}
//if it's december the 31st, set the date to january 1st
if (isMonth31 && this.dayFristDay == 30) {
this.dayFristDay++;
System.out.println("");
return;
}
//if the month has 31 days, but it is the 30st, just advance the day.
if (!isMonth31 && this.dayFristDay == 30) {
this.monthFirstDay++;
this.dayFristDay = 1;
System.out.println("");
return;
//if the month has 30 days and it is the 30st, advance the month and set the day to one.
}
}
if (this.dayFristDay == 28 && this.monthFirstDay == 2) {
this.monthFirstDay++;
this.dayFristDay = 1;
System.out.println("");
return;
}
//if it's the 28st of february, advance to march the first.
System.out.println("");
this.dayFristDay++;
}
这些打印内容是调试器的断点。如果任何if语句为true,则我永远都不应最后打印。但是我一直走到最后一次打印,虽然这不应该这样做。
编辑:重现该错误: //在同一包中的不同类中使用 座舱测试CP =新座舱(28,2); testCP.advanceDay();
public class Cockpit {
private int dayFristDay;
private int monthFirstDay;
public Cockpit(int dayFristDay, int monthFirstDay) {
this.dayFristDay = dayFristDay;
this.monthFirstDay = monthFirstDay;
}
//advanceDay method as a above
protected String getCurrentDay() {
return this.dayFristDay + "-" + this.monthFirstDay;
}
}
答案 0 :(得分:4)
Cockpit testCP = new Cockpit(28, 2);
this.testCP.advanceDay();
第2行未在您在第1行创建的实例上调用advanceDay
。您正在某个成员变量所引用的实例上调用它。
删除this
。