首页 > 解决方案 > 为什么返回语句不退出方法?

问题描述

我正在使用 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;
     }
}

标签: javareturn

解决方案


Cockpit testCP = new Cockpit(28, 2);    
this.testCP.advanceDay();

第 2 行没有调用advanceDay您在第 1 行创建的实例。您是在某个成员变量引用的实例上调用它。

删除this.

Ideone 演示,显示返回有效


推荐阅读