繁体   English   中英

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

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

好久没碰java了。 我需要一些帮助,我想用这个程序做的是让汽车类计算 getcarbonfootprint() 方法内的碳足迹。 然而,就像我经历过的所有视频一样,我不想通过返回值将它传回主类。 相反,我想通过方法在类汽车中使用相同的变量。 我尝试使用 this 值,但是,这也不起作用。 如果您可以将我链接到此问题的正确位置,那也将起作用。

主要课程:

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

汽车等级:

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

需要在getcarbonfootprint()之前调用您的方法returncarbonfootprint()

您应该先调用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