简体   繁体   English

在方法之间传递同一个类中的变量?

[英]Passing variables in the same class between methods?

I havent touched java in awhile.好久没碰java了。 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.我需要一些帮助,我想用这个程序做的是让汽车类计算 getcarbonfootprint() 方法内的碳足迹。 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.我尝试使用 this 值,但是,这也不起作用。 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()需要在getcarbonfootprint()之前调用您的方法returncarbonfootprint()

You should call getcarbonfootprint() first, it will generate and set value to variable carbonfootprint and then call returncarbonfootprint() to get updated value.您应该先调用getcarbonfootprint() ,它会生成并将值设置为变量 carbonfootprint,然后调用returncarbonfootprint()以获取更新的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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