CarTest.java Answers

Click here to go back to the questions
// ANSWERS:
//
// (1) What does the line "serial++" do in the constructor for class Car?
// 

// It increases the static property "serial", each time a car
// is constructed, so that each car object gets a unique serial
// number.

// 
// (2) Write toString methods for the Car and Driver classes so that
// you use them in the next question for debugging.
// 

// Method for Car class:
public String toString()
{
   return ("I am a car model=" + model +
           ", value=" + value +
           ", serial number=" + serialNumber);
}
// Method for Driver class:
public String toString()
{
   return ("I am a driver, name=" + name +
           ", money=" + money +
           ", car=(" + ownersCar.toString() + ")");
}

// 
// (3) Write the methods listed in the main method.
// 

// Methods for the class Driver:
public void purchase(Car aCar)
{
   ownersCar = aCar;
   money -= aCar.value;
}
public void stealCarFrom(Driver victim)
{
   ownersCar = victim.ownersCar;
   victim.ownersCar = null;
}
public void smashCar()
{
   ownersCar.value = ownersCar.value / 2;
}
public static void swapMoney(Driver d1, Driver d2)
{
   int tempMoney = d1.money;
   d1.money = d2.money;
   d2.money = tempMoney;
}
public static void swapCars(Driver d1, Driver d2)
{
   Car tempCar = d1.ownersCar;
   d1.ownersCar = d2.ownersCar;
   d2.ownersCar = d1.ownersCar;
}
// Method belongs in class Car:
public static void swapSerialNumbers(Car c1, Car c2)
{
   int tempSerialNumber = c1.serialNumber;
   c1.serialNumber = c2.serialNumber;
   c2.serialNumber = tempSerialNumber;
}
// Methods for the class Driver:
public void tradeIn(Car aCar)
{
   money = money + ownersCar.value/2;
   ownersCar = aCar;
}
public void sellCarTo(Driver buyer)
{
   buyer.money = buyer.money - ownersCar.value;
   money = money + ownersCar.value;
   buyer.ownersCar = ownersCar;
   ownersCar = null;
}
public int netWorth()
{
   if (ownersCar == null)
   {
      return money;
   }
   else
   {
      return money + ownersCar.value;
   }
}

//