java - 为什么返回语句不退出方法?
问题描述
我正在使用 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 语句为真,我将永远不会到达最后一次打印。但是我一直在进行最后一次打印,虽然它不应该这样做。
编辑:重现错误://在同一个包中的不同类中使用 Cockpit testCP = new Cockpit(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;
}
}
解决方案
Cockpit testCP = new Cockpit(28, 2);
this.testCP.advanceDay();
第 2 行没有调用advanceDay
您在第 1 行创建的实例。您是在某个成员变量引用的实例上调用它。
删除this
.
推荐阅读
- html - 响应式 div 框
- gremlin - 如何删除具有相同标签名称的所有顶点的属性?
- php - 使用 XAMPP 在 MacOS Catalina 中启用 intl 时出现问题
- docker - 如何读取 solr.properties 中的环境变量
- reactjs - React 守卫更改路线但不显示组件
- wordpress - 在 WordPress 中管理子目录的最佳实践是什么?
- javascript - 如何避免 JavaScript 日期格式错误
- javascript - 有没有办法更改 JS/TS mocha 测试的添加测试后缀
- javascript - 在 Nest JS 中模拟 HTTP 拦截器
- nlp - 如何在 Azure 认知搜索中对 blob 文档进行分页索引?