简体   繁体   中英

Passing variables in the same class between methods?

I havent touched java in awhile. I need some help, what I am trying to do with this program is get the car class to calculate the carbonfootprint inside of the getcarbonfootprint() method. HOWEVER, like all the videos that I have been going through, I DON'T want to pass it back to the main class through a return value. Instead, I want to use the same variables in the class car through methods. I tried using the this value, however, that doesn't work either. If you can link me to the right location on this question, that will work as well.

MAIN CLASS:

package carbonfootprinttest;

public class CarbonFootprinttest {

    public static void main(String[] args) {
        building house = new building();
        car fusion = new car();
        bike trek = new bike();
        double mytest = fusion.returncarbonfootprint();
        System.out.print(mytest);
    }
}

CAR CLASS:

public class car implements carbonfootprint {
    private double mpg = 25;
    public double yearly = 500;
    public double carbonfootprint;

    public void setmpg(){
        System.out.println("The mpg of a ford fusion is " + mpg + " MPG.");
    }

    @Override
    public void getcarbonfootprint() {
        carbonfootprint = (yearly * mpg)/9;
    }
    public double returncarbonfootprint(){
        System.out.println(carbonfootprint);
        return carbonfootprint;
    }
}
package carbonfootprinttest;

public class CarbonFootprinttest {
    public static void main(String[] args) {
    building house = new building();
    car fusion = new car();
    bike trek = new bike();
    fusion.getcarbonfootprint();
    double mytest = fusion.returncarbonfootprint();
    System.out.print(mytest);
}

Need to call your method getcarbonfootprint() before returncarbonfootprint()

You should call getcarbonfootprint() first, it will generate and set value to variable carbonfootprint and then call returncarbonfootprint() to get updated value.

fusion.getcarbonfootprint();//Add this line of code in main method
    double mytest = fusion.returncarbonfootprint();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM