Reputation: 5
I have a car class which is as follows:
public class Car {
private String reg = null;
double[] tyre = {0.0,0.0,0.0,0.0};
public Car(String reg, double[] tyre) {
super();
this.reg = reg;
this.tyre = tyre;
}
public double calculateAverageTyrePressure() {
double p = tyre[0] + tyre[1] + tyre[2] + tyre[3];
return p/4.0;
}
}
and I have a test class where I have created an object and would like to give it 4 decimal values for it's tyre pressure but I can't figure out how to enter the values without getting an error as If i enter 4 decimal values it wants me to change my constructor to (String, double, double, double, double) which is not what the task says to do.
Test class:
public class CarTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Car car1 = new Car("V380 FEL", !!Need tyre values here!!);
}
}
P.S sorry If this seems like an easy question I've just started with Java and trying to learn.
Upvotes: 0
Views: 89
Reputation: 447
To answer the immediate question, your constructor takes an array and if you do something like
new Car("hooptie", 32.0, 32.0, 32.0, 32.0)
the error, as you've already seen is complaining that it can't find a matching constructor.
One option is to do:
new Car("Hooptie", new double[]{32.0, 32.0, 32.0, 32.0}) ;
That said, i think we have an opportunity here to improve your API a little. How the Car class chooses to store the tyres is really up to the car class. I'm not sure we want to leak that out to the code using the car class.
For example, what happens if I, as someone using your car class, does this:
new Car("7 wheeler", new double[]{32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0 } )
Should that be allowed? I dunno, that's up to you.
An alternate option would be to create a constuctor that took in 4 tyre parameters and then you added them to your internal tyre array.
new Car(String name, double tyrePressureOne, double tyrePressure2... ) {
this.name = name;
tyres[0] = tyrePressureOne;
...
}
Upvotes: 1
Reputation: 16866
Try Car car1 = new Car("V380 FEL", new double[] { 0.0, 0.0, 0.0, 0.0});
. You need to initialize a Java array with all four of your decimal values inside of it, so that you satisfy the current constructor.
Upvotes: 3