适合初学者的Java汽车类

时间:2015-02-19 00:46:06

标签: java class

我必须实现具有以下属性的类Car。汽车具有一定的燃料效率(以英里/加仑或升/公里 - 一次测量)和燃气罐中的一定量的燃料。效率在构造器中指定,并且初始燃料水平为0.提供模拟驾驶汽车一定距离的方法驱动器,减少燃料箱中的汽油量。还提供方法getGasInTank,返回燃油箱中当前的汽油量,并添加汽油,将汽油添加到油箱。

我已经为汽车创建了一个类和一个测试程序来插入一些值,当我运行程序时,我得到的是我输入的addGas值。每加仑英里的计算将不会运行我不懂为什么。你可以告诉我,我对java非常陌生,对此问题的任何帮助都非常感激。

    public class CarTest
{
public static void main(String[] args)
  {
    Car richCar = new Car(49);

    richCar.addGas(15);
    richCar.drive(150);
    System.out.println(richCar.getGas());
  }
}





    /**
A car can drive and consume fuel
*/
public class Car
{
/**
  Constructs a car with a given fuel efficiency
  @param anEfficiency the fuel efficiency of the car
*/
public Car(double mpg)
{
  milesPerGallon = mpg;
  gas = 0;
  drive = 0;
}

 /** Adds gas to the tank.
   @param amount the amount of fuel added
 */
 public void addGas(double amount)
 {
  gas = gas + amount;
 }

 /**
   Drives a certain amount, consuming gas
   @param distance the distance driven
 */
 public void drive(double distance)
 {
  drive = drive + distance;
 }

 /**
   Gets the amount of gas left in the tank.
   @return the amount of gas
  */

 public double getGas()
 {
  double mpg;
  double distance;
  distance = drive;
  mpg = gas * milesPerGallon / distance;
  return gas;
 }

  private double drive;
  private double gas;
  private double milesPerGallon;
}

4 个答案:

答案 0 :(得分:0)

计算就好了。不过,你的方法只是返回气体的一个值。

这可以用一些清理;我建议摆脱所有的挫折,然后重新计算。

public double calculateGas() {
    return (gas * milesPerGallon) / drive;
}

答案 1 :(得分:0)

您的测试程序只调用三种方法:

richCar.addGas(15);
richCar.drive(150);
System.out.println(richCar.getGas());

让我们来看看每个人做了什么。

addGas(15)修改您的气体实例变量。

drive(150)仅执行第drive = drive + distance;

getGas()似乎做了一些事情,超出预期(人们会期望它只返回gas,但它也会计算并存储最新的mpg值)。但是如果你检查getGas()气体的代码从未被修改过,那么只返回。

所以你调用了三种方法,在这三种方法中,当你用richCar.addGas(15)将气体设置为15时,气体只被修改一次。

如果drive(int)方法基于某个设定的mpg值修改gas,而不是仅跟踪驱动的英里数,那么看起来最简单,然后你就可以{{1}只需返回drive()

这意味着您也可以摆脱gasmpg的修改,这很好,因为无论计算使用多少气体,都需要该值。如果你有更多的逻辑改变了使用了多少气体但你还没有使用它,你可能会引入一个getGas()值。

答案 2 :(得分:0)

结合一些想法......

/**
Drives a certain amount, consuming gas
@param distance the distance driven
*/
public void drive(double distance)
{
    drive = drive + distance;
    gas = gas - (distance / milesPerGallon);
}

/**
Gets the amount of gas left in the tank.
@return the amount of gas
*/

public double getGas()
{
    return gas;
}

答案 3 :(得分:-1)

看起来你的问题就在这里

public double getGas()
{
double mpg;
double distance;
distance = drive;
mpg = gas * milesPerGallon / distance;
return gas;
}

你正在对mpg进行计算,但是你最后会返回gas属性。

除了第一次添加气体之外,它实际上似乎并没有改变气体的值。

相关问题