如何从相同的 JAVA class 调用返回值

How to call a returned value from the same JAVA class

我在做时间比较项目,我用了一种非常愚蠢的方法来做。请看下面的代码:

在函数getInDays中,我计算了一年有多少天,并设置了天数。但是,在名为 getInHours 的下一个函数中,不能使用天数。有人可以帮助我吗?

非常感谢!

PS:为了让这段代码更容易看懂,我已经删除了所有其他函数。

package datetimeexample;

public class DateTime {
    private int month;
    private int day;
    private int year;
    private Time time;


    public void getInDays()
    {
        int days = year * 365 + month * 31 + day;
    }

    public void getInHours()
    {
        int totalHours = days*12 + time.getHour();
    }


}

days 是在 getInDays() 方法中声明的。天的范围是 getInDays() 的本地范围 methods.It 无法从该方法外部访问。

您有 2 个选择。

  1. 在 getInDays() 方法之外声明 days 并使其范围成为实例级别。

  2. 而不是在 getInHours() 中使用 days 直接调用 getInDays()。 (前提是你改变了方法的return类型。

Check this link for more info