我有一项任务是编写一个程序来根据汽车的三次填充来预测每年的燃料使用量。我必须使用两个单独的类。这是我的第一堂课,名为AnnualFuelUse。
public class AnnualFuelUse
{
private static int endMiles, startMiles,fillUp, days,distance;
private double gallonsUsed, pricePerGallon,MPG,cost;
AnnualFuelUse(int fu, int d, int sm, int em, double gu, double price)
{
fillUp = 0;
days = d;
startMiles = sm;
endMiles = em;
gallonsUsed = gu;
pricePerGallon = price;
distance = 0;
MPG = 0.0;
cost = 0.0;
}
public void calcDistance ()
{
distance = endMiles - startMiles;
}
public int getDistance(){
return distance;
}
//calculates miles per gallon
public void calcMPG()
{
MPG = distance /gallonsUsed;
}
public double returnMPG(){
return MPG;
}
public void totalCost(){
cost= gallonsUsed * pricePerGallon;
}
public double getCost(){
return cost;
}
public int returnStart(){
return startMiles;
}
public int returnEnd(){
return endMiles;
}
public int returnDays(){
return days;
}
public double returnGallons(){
return gallonsUsed;
}
public double returnPrice(){
return pricePerGallon;
}
}
这是我的第二堂课,名为AnnualFuelUseTester。 (对不起长名,但这是必需的)
public class AnnualFuelUseTester
{
public static void main(String[]args)
{
AnnualFuelUse[]fuel = {new AnnualFuelUse(1,1,45023,45231,10.00,2.95),
new AnnualFuelUse(2,4,45231,45480,11.70,2.99),
new AnnualFuelUse(3,8,45480,45659,9.30,3.01),
new AnnualFuelUse(4,13,45659,45961,14.90,3.01)};
for (int index = 0; index<fuel.length;index++)
{
fuel[index].calcDistance();
fuel[index].calcMPG();
fuel[index].totalCost();
}
System.out.println(" Fill Up Days Start Miles End Miles Distance Gallons Used MPG Price Cost ");;
for(int index = 0; index < fuel.length; index++)
{
System.out.printf("%5d %6d %9d %12d %12d %10.2f %13.1f %6.2f %6.2f \n",
index+1,fuel[index].returnDays(),fuel[index].returnStart(),fuel[index].returnEnd(),fuel[index].getDistance(),fuel[index].returnGallons(),fuel[index].returnMPG(),fuel[index].returnPrice(),fuel[index].getCost());
}
我的问题是,当我运行程序时,日期,起始里程,结束里程和距离列都包含相同的数字,最后一个填充的数据。使用的加仑,MPG,价格,成本,都可以正常工作。所以在Days专栏中,不是阅读1,4,8,13,而是读取13,13,13,13。
我很感激帮助解决这个问题。
答案 0 :(得分:1)
您的字段不应该是静态的。这意味着每个班级(不是实例)
private static int endMiles, startMiles,fillUp, days,distance;
应该是
private int endMiles, startMiles,fillUp, days,distance;