I have this simple class that creates a vehicle with three instances (brand, tank capacity and fuel consumption -l/100km-). These are public, and objects can be created with the constructor below:
public class VehicleClass
{
String brand;
int tank;
double consumption;
VehicleClass (String brand, int tank, double consumption)
{
this.brand = brand;
this.tank = tank;
this.consumption = consumption;
}
}
I want to create an array containing two vehicles, so in the main class, I create these three objects:
public class VehicleMain
{
public static void main (String[] args)
{
VehicleClass car1 = new VehicleClass ("Ford", 40, 6.5);
VehicleClass car2 = new VehicleClass ("Volkswagen", 50, 5.0);
VehicleClass cars[] = new VehicleClass[] {car1, car2};
}
}
I want to create a method, that using the array cars, will return an array of the maximum range of both vehicles. This is my approach:
public int[] distances (VehicleClass[] car)
{
int[] range = new int[car.length];
for (int i = 0; i < car.length; i++)
{
range[i] = (int) ((tank * 100) / consumption);
}
return range;
}
Accessing this method in the main class with the import java.util.Arrays:
System.out.println (Arrays.toString (car<number>.distances(cars)));
However, I only get [615, 615] if I put car1, and [1000, 1000] with car2. And my goal is that it will return [615, 1000].
Putting this, gives me an error:
System.out.println (Arrays.toString (cars.distances(cars)));
What am I doing wrong? Is it possible to do what I was thinking? I would really appreciate if someone could clarify me this question. I'm a beginner at OOP.
distancesmethod, you mean to make use ofcar[i].tankandcar[i].consumption. Currently you are only using thetankandconsumptionof object that received thedistancesmethod call.creates a vehicle with three instances (brand, tank capacity and fuel consumption -l/100km-). I think you meanvehicle with three fieldsVehicle#distance, which returns the distance for a single vehicle. Then it's just a matter of making an array of those distances for the array of inputs. At the moment, you're trying to combine the concepts.VehicleClass cars[]is discouraged, the recommended syntax isVehicleClass[] cars.