Post

Created by @nathanedwards
 at November 3rd 2023, 7:27:50 pm.

Question:

Suppose you are designing a program to simulate a car race using object-oriented programming in Java. You have created a class called Car with the following instance variables:

- `String make`: represents the make of the car
- `int year`: represents the year the car was manufactured
- `double topSpeed`: represents the top speed of the car in kilometers per hour

Assuming that the class has a parameterized constructor and appropriate getter and setter methods for all instance variables, write a method called `race` that takes an array of Car objects as a parameter and returns the car with the highest top speed.

The method signature is given below:

```java
public static Car race(Car[] cars)

Write the method race with the given signature as well as any additional helper methods or variables you may need. Your implementation should return null in case the cars array is empty.

Example Usage:

Car[] cars = {
    new Car("Ferrari", 2021, 320.5),
    new Car("Porsche", 2020, 314.2),
    new Car("Lamborghini", 2019, 330.0),
    new Car("McLaren", 2022, 335.9)
};

Car fastestCar = race(cars);
System.out.println(fastestCar.toString()); // Output: McLaren, 2022, 335.9

Explanation:

To solve this problem, we can iterate over the cars array while keeping track of the car with the highest top speed. Initially, we can set the highest top speed as the first car's top speed.

  1. Start the race method with the given signature. Create a variable called fastestCar and initialize it as null.
  2. Check if the cars array is empty. If it is, return null.
  3. Initialize the fastestCar variable with the first car from the cars array. We can assume that the cars array is not empty, so this step is valid.
  4. Iterate over the cars array starting from index 1 (since we already assigned the first car as the fastestCar).
    • Inside the loop, compare the top speed of the current car with the top speed of fastestCar.
    • If the current car's top speed is greater than fastestCar's top speed, update the fastestCar variable with the current car.
  5. After the loop ends, fastestCar will contain the car with the highest top speed. Return fastestCar.

Here's the implementation of the race method:

public static Car race(Car[] cars) {
    Car fastestCar = null;

    if (cars.length == 0) {
        return null;
    }

    fastestCar = cars[0];

    for (int i = 1; i < cars.length; i++) {
        if (cars[i].getTopSpeed() > fastestCar.getTopSpeed()) {
            fastestCar = cars[i];
        }
    }

    return fastestCar;
}