X984: Object Oriented Design 2

For this question, you will be working within the Person class.

public class Person
{
    public Car car;

    public Person(Car c)
    {
        this.car = c;
    }
}

A Person has a field called car that refers to a Car object.

public class Car
{
    //  number of miles the car can go with a full tank
    private int totalMiles;

    // number of miles left before we need to get gas
    private int milesUntilGas;

    // initially has a full tank of gas
    public Car(int miles)
    {
        this.totalMiles = miles;
        this.milesUntilGas = miles;
    }

    /**
     * Drivess car the car the specified number of miles.
     * We can't drive more miles than we have gas for.
     *
     * @param miles, int number of miles to drive
     * @return true if car successfully drives, otherwise false
     */
    public boolean drive(int miles)
    {
        if (miles <= this.milesUntilGas)
        {
            this.milesUntilGas = this.milesUntilGas - miles;
            return true;
        }
        return false;
    }

    /**
     * Represents filling up the gas tank of the car.
     */
    public void fillUpGasTank()
    {
        this.milesUntilGas = totalMiles;
    }
}

This Car class has two notable methods.

  • A drive method that represents driving the number of miles passed as a parameter (if possible)
  • a fillUpGasTank method that resents the number of miles the car can drive to its maximum.

For example, if we created a car object that could drive a maximum of 50 miles before needing gas, running drive(10) would mean we could drive 40 more miles before we need to get gas. We can see this is a boolean method where if we can drive the inputted amount, the method returns true.

If we tried to go further than the car could drive, though, this method would return false.

Car c = new Car(50); // the car can drive a maximum of 50 miles
boolean firstDrive = c.drive(30); // returns true, can now drive 20 more miles
boolean secondDrive = c.drive(30); // returns false - drive unsuccessful.

For this question, we will be creating a goToStore() method that should attempt to drive the number of miles passed in as a parameter.

Create a conditional to support the following logic:

  • If the first drive to the store is not successful (meaning didDrive is false), get gas and try to drive again

Your Answer:

Feedback

Your feedback will appear here when you check your answer.