[英]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.