instance variable stay long, but local variable only stay short term.
public class CarTester
{
public static void main(String[] args)
{
Car car = new Car();
// TODO: Add 20 gallons and drive 100 miles
car.addGas(20);
car.drive(100);
// TODO: Print actual and expected gas level
System.out.println("Expected:18");
System.out.println(car.getGasInTank());
}
}
public class Car
{
private double milesDriven;
private double gasInTank;
private double milesPerGallon;
public Car()
{
milesDriven = 0;
gasInTank = 0;
milesPerGallon = 50;
}
/**
Drives this car by a given distance.
@param distance the distance to drive
*/
public void drive(double distance)
{
milesDriven = milesDriven + distance;
double gasConsumed = distance / milesPerGallon;
gasInTank = gasInTank - gasConsumed;
}
public void addGas(double amount)
{
gasInTank = gasInTank + amount;
}
/**
Gets the current mileage of this car.
@return the total number of miles driven
*/
public double getMilesDriven()
{
return milesDriven;
}
/**
Gets the current amount of gas in the tank of this car.
@return the current gas level
*/
public double getGasInTank()
{
return gasInTank;
}
}