I am creating a class called Car
with a method called TotalPrice
which will take an array of Car
s and calculate the total for the list. I have implemented a client method totalPrice
, which accepts a list (ArrayUnsortedList carList
) of cars and returns an integer equal to the total cost of the cars on the list.
I am stuck on writing the test driver so that I can test my actual Car
class program.
Here's my code for the Car
class:
public class Car
{
int year;
String make;
String model;
int price;
public Car(int year, String make, String model, int price) {
this.year = year;
this.make = make;
this.model = model;
this.price = price;
}
public int getYear() {
return this.year;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getPrice() {
return this.price;
}
public static int totalPrice(ArrayUnsortedList carList) {
int totalPrice = 0;
for(int i=carList.size(); i>0; i--)
{
totalPrice += ((Car)carList.getNext()).getPrice();
}
return totalPrice;
}
}
Here's my test drive class:
import java.util.Scanner;
import java.util.ArrayList;
public class CarList{
public static void main (String [] args) {
ArrayUnsortedList<Car> carList = new ArrayUnsortedList<Car>();
Car car1, car2;
car1 = new Car(2016, "BMW", "M4", 65700);
carList.add(car1);
car1 = new Car(2016, "Mercedes-Benz", "C300", 38950);
carList.add(car1);
car2 = new Car(2016, "Lexus", "GS F", 84440);
carList.add(car2);
System.out.println(Car.totalPrice(carList));
}
}
UPDATE********
I have to use ArrayUnsortedList that is given.
Here are the rest of the codes: GITHUB
UPDATE Now I am getting the wrong totalPrice?
65700 + 38950 + 84440 = 189090
But I get 253320???
----jGRASP exec: java CarList
253320
----jGRASP: operation complete.
For the code of the totalPrice
function itself, I would use ArrayUnsortedList.size()
and ArrayUnsortedList.getNext()
to browse the list content. This list api is terrible (intentionally, I suppose) and it's understandable you had a little difficulties here. Learn to quickly browse a Java class, looking only at the function headers to determine which function can be useful.
int totalPrice = 0;
for(int i=carList.size(); i>0; i--)
{
totalPrice += carList.getNext().getPrice();
}
return totalPrice;
You will notice I do not reference i
inside the loop ; that's because there is no method of ArrayUnsortedList
that expects an index. So I just rely on i
to make sure I make the good number of calls to ArrayUnsortedList.getNext()
.
On other topics,
I don't think it's the job of the Car class to sum the price of cars. totalPrice
should imo be implemented as a function on the ArrayUnsortedList
or simply executed as is in your test class.
I think tests in Java environment should be run with JUnit. This might be a topic you'll soon encounter, but if you've already worked with JUnit then your test runner should use it.