MIT | MIT-AITI | Ethiopia 2004

Java Lab 8: Racecar - Part I

  1. Create a new class called Racecar. Add two fields to Racecar: a field of type String to store the name of the car and a field of type Color (from java.awt.Color) to store the color of the car. Each car can have a different name and color. Should the fields be static or non-static? Compile.
  2. Every one of our racecars will have the same top speed. Add a private constant of type double to the Racecar class to store the top speed and initialize it to any number you want. Should this field be static or non-static? Compile.
  3. Add a constructor to Racecar which accepts a name and color argument and assigns the arguments to the name and color fields of the class. Compile.
  4. Add a method called getName that returns the name of the car and a method called getColor that returns the color of the car. Should these methods be static or non-static? Compile.
  5. Add a method to Racecar called race which accepts two Racecars as arguments, simulates a race between the two, and returns the car that wins the race, or null if the race is a tie. The method should calculate a random speed for each car between 0 and the top speed. The car with the higher speed wins the race, but if they both have the same speed they tie. The method random in java.lang.Math returns a random double between 0 and 1. If you multiply this random number by the top speed, the product will be a random number between 0 and the top speed. Should this method be static or non-static? Compile.
  6. Add a main method to Racecar which creates two Racecars, races them against one another, and prints out the winner's name. When instantiating the Racecar objects, pass one of the static fields of the Color class (like RED or BLUE) as the color argument to the constructor. Should the main method be static or non-static? Compile and run.
  7. (Optional) Instead of having a constant top speed for all racecars, change the Racecar class so every car has its own top speed.
  8. (Optional) Program a better racing simulation in the race method.

Submission: Submit all of your code for this lab.

Hosted by www.Geocities.ws

1