【发布时间】: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