【问题标题】:Passing variables in the same class between methods?在方法之间传递同一类中的变量?
【发布时间】:2016-04-01 06:31:07
【问题描述】:

我好久没接触java了。我需要一些帮助,我试图用这个程序做的是让汽车类计算 getcarbonfootprint() 方法内部的碳足迹。但是,就像我浏览过的所有视频一样,我不想通过返回值将它传递回主类。相反,我想通过方法在类 car 中使用相同的变量。我尝试使用 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;
    }
}

【问题讨论】:

  • this.your_variable 应该可以工作:this.carbonfootprint = carbonfootprint
  • Java 中有一些被广泛使用的style and naming conventions。例如,接口和类名应采用 UpperCamelCase。此外,方法名称不应以return 开头。我建议您将returncarbonfootprint() 重命名为carbonFootprint()get 方法通常会返回一些东西。 getcarbonfootprint() 应重命名为 recalculateCarbonFootprint()。注意名称对于编写可维护的代码非常重要。
  • @aetheria 谢谢!我现在正在为最终产品进行更改!

标签: java class variables methods


【解决方案1】:
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);
}

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

【讨论】:

  • 谢谢你们两个在同一时间给出了很好的答案。
【解决方案2】:

你应该先调用getcarbonfootprint(),它会生成并设置变量carbonfootprint的值,然后调用returncarbonfootprint()获取更新的值。

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

【讨论】:

  • 谢谢你们两个在同一时间给出了很好的答案。
猜你喜欢
  • 1970-01-01
  • 2013-10-30
  • 2012-03-20
  • 2018-08-08
  • 1970-01-01
  • 2015-04-03
相关资源
最近更新 更多