Je crée une classe appelée Car
avec une méthode appelée TotalPrice
qui prendra un tableau de Car
s et calculera le total de la liste. J'ai mis en œuvre une méthode client totalPrice
, qui accepte une liste (ArrayUnsortedList carList
) de voitures et renvoie un nombre entier égal au coût total des voitures sur la liste.Comment puis-je obtenir le prix total de ma carList?
Je suis bloqué sur l'écriture du pilote de test afin que je puisse tester mon vrai programme de classe Car
.
Voici mon code pour la classe Car
:
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;
}
}
Voilà ma classe d'essai routier:
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));
}
}
MISE À JOUR ********
Je dois utiliser ArrayUnsortedList qui est donné.
Voici le reste des codes: GITHUB
MISE À JOUR Maintenant, je reçois le mauvais TotalPrice?
65700 + 38950 + 84440 = 189090
Mais je reçois 253320 ???
----jGRASP exec: java CarList
253320
----jGRASP: operation complete.
'Car.totalPrice (carList)'? – skypjack
@skypjack Je ne peux pas l'utiliser car il est incompatible avec mon ArrayUnsortedList – pyuntae
Eh bien, construisez un 'ArrayUnsortedList' de l'autre liste ou définissez un constructeur qui accepte une liste générique, puis utilisez-le. – skypjack