Mi Le
Mi Le

Reputation: 13

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

I'm a beginner and I am learning how to retrieve values from void methods with another "getter" method in java. However, this time, it keeps on returning 0.0. I'm not sure what I did wrong.

Constructor 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;
}

Tester class:

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

If I change the void to double and "return" instead of "t =" with gas.tons() in the main method, then it would work but I am require to have the getter method. I don't understand why it only returns 0.0.

Upvotes: 1

Views: 2708

Answers (3)

Jay Guyll
Jay Guyll

Reputation: 35

Your contructor sets t = 0.0. Then you simply ask for the value of your private variable t, without ever manipulating the value. At some point you would need to call tons() in order to calculate the gallons into the value of t.

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

Would return a calculated value, or you could add the call to tons() inside the constructor method.

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

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

public double getT()
{
  return t;
}

Upvotes: 0

Mureinik
Mureinik

Reputation: 311163

You don't need a tons() method. Frankly, you don't even need to store the tons - just perform the calculation on the fly:

public class CO2 {
    private double gallons;

    public CO2() {
        gallons = 1288.0;
    }

    public double getGallons() {
        return gallons;
    }

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

Upvotes: 3

arjunsv3691
arjunsv3691

Reputation: 829

When you create an object of your class the instance variable are initialized with the values in the constructor, so value of t is 0.

However you are changing the value of t in method named tons, so in order to change the value of t you should call that method, else it would remain zero.

To change the value of t it's always good to use a setter method. If you are sure that value will be always a constant and won't change then set that value in constructor itself.

Upvotes: 0

Related Questions