使用另一个 void 方法的变量从方法中获取值

Getting value from a method with the variable from another void method

我是初学者,我正在学习如何使用 java 中的另一个 "getter" 方法从 void 方法中检索值。然而,这一次,它继续返回 0.0。我不确定我做错了什么。

构造函数class:

private double gallons;
private double t;

public CO2()
{
  gallons = 1288.0;
  t = 0.0;
}

public void tons()
{
  t = gallons * 8.78e-3;
}

public double getT()
{
  return t;
}

测试员class:

CO2 gas = new CO2;
System.out.print(gas.getT());

如果我在 main 方法中将 void 更改为 double 和 "return" 而不是 "t =" 和 gas.tons(),那么它会起作用,但我需要 getter方法。我不明白为什么只有 returns 0.0.

当您创建 class 的对象时,实例变量会使用构造函数中的值进行初始化,因此 t 的值为 0。

但是,您要在名为 tons 的方法中更改 t 的值,因此为了更改 t 的值,您应该调用该方法,否则它将保持为零。

要更改 t 的值,最好使用 setter 方法。如果您确定该值将始终为常量并且不会更改,则在构造函数本身中设置该值。

您的构造函数设置 t = 0.0。然后您只需询问您的私有变量 t 的值,而无需操纵该值。在某些时候,您需要调用 tons() 才能将加仑计算为 t 的值。

CO2 gas = new CO2;
gas.tons();
System.out.print(gas.getT());

将 return 计算值,或者您可以在构造方法中添加对 tons() 的调用。

public CO2()
{
  gallons = 1288.0;
  t = 0.0;
  tons();
}

public void tons()
{
  t = gallons * 8.78e-3;
}

public double getT()
{
  return t;
}

您不需要 tons() 方法。坦率地说,您甚至不需要存储吨数 - 只需即时执行计算即可:

public class CO2 {
    private double gallons;

    public CO2() {
        gallons = 1288.0;
    }

    public double getGallons() {
        return gallons;
    }

    public double getTons() {
        return gallons * 8.78e-3;
    }
}