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.
race
method with the given signature. Create a variable called fastestCar
and initialize it as null
.cars
array is empty. If it is, return null
.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.cars
array starting from index 1 (since we already assigned the first car as the fastestCar
).
fastestCar
.fastestCar
's top speed, update the fastestCar
variable with the current car.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;
}