Java 汽车 class 初学者

Java car class for beginner

我必须实现具有以下属性的 class 汽车。汽车具有一定的燃油效率(以 miles/gallon 或 liters/km 衡量——选择一个)和油箱中一定量的燃油。效率在构造函数中指定,初始油位为 0。提供模拟驾驶汽车一定距离的方法 drive,减少油箱中的汽油量。还提供方法 getGasInTank,返回当前油箱中的汽油量,以及 addGas,向油箱添加汽油。

我已经为汽车创建了一个 class 和一个测试程序来插入一些值,当我 运行 我得到的程序返回的只是我输入的 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;
}

看来您的问题出在这里

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

您正在计算 mpg,但最后返回的是汽油 属性。

除了第一次添加 gas 的时候,你似乎并没有在任何地方改变 gas 的值。

计算就好了。不过,您的方法只是 返回 gas 的一个值。

这可能需要一些清理工作;我建议摆脱所有的麻烦,只返回计算。

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

你的测试程序只调用了三个方法:

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

让我们来看看每个人的作用。

addGas(15) 修改你的 gas 实例变量。

drive(150) 只执行行 drive = drive + distance;

getGas() 似乎做了一些事情,比预期的要多(人们会期望它只是 returns gas 但它也计算并存储最新的 mpg 值)。但是如果你检查 getGas() gas 的代码从未被修改,只有 returned.

所以你调用了三个方法,在这三个执行中 gas 只被修改一次,当你用 richCar.addGas(15).

将它设置为 15 的值时

如果 drive(int) 方法根据一些设置的 mpg 值修改 gas,而不是只记录行驶了多少英里,那么这似乎最简单,然后你可以 drive() 只是 return gas.

这意味着您也可以摆脱在 getGas() 中修改 mpg,这很好,因为无论计算使用多少 gas,都需要该值。如果你有更多的逻辑来改变使用多少 gas 但你还没有那个,你也许可以引入一个 actualMpg 值。

结合一些想法...

/**
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;
}