[英]How do I get the total price from my carList?
我正在使用名為TotalPrice
的方法創建一個名為Car
的類,該方法將使用Car
的數組並計算列表的總數。 我已經實現了一個客戶端方法totalPrice
,它接受汽車列表( ArrayUnsortedList carList
)並返回一個等於列表上汽車總成本的整數。
我堅持編寫測試驅動程序,以便可以測試實際的Car
類程序。
這是我的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;
}
}
這是我的試駕課:
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));
}
}
更新********
我必須使用給定的ArrayUnsortedList。
以下是其余代碼: GITHUB
更新 現在我得到了錯誤的totalPrice?
65700 + 38950 + 84440 = 189090
但我得到253320 ???
----jGRASP exec: java CarList
253320
----jGRASP: operation complete.
對於totalPrice
函數本身的代碼,我將使用ArrayUnsortedList.size()
和ArrayUnsortedList.getNext()
瀏覽列表內容。 這個列表API很糟糕(我想是故意的),可以理解,您在這里遇到了一些困難。 學習快速瀏覽Java類,僅查看函數頭以確定哪個函數有用。
int totalPrice = 0;
for(int i=carList.size(); i>0; i--)
{
totalPrice += carList.getNext().getPrice();
}
return totalPrice;
您會注意到,我沒有在循環內引用i
; 那是因為沒有ArrayUnsortedList
方法需要索引。 所以我只是依靠i
來確保對ArrayUnsortedList.getNext()
進行了大量的調用。
在其他主題上
我認為總結汽車價格不是汽車課的工作。 totalPrice
應該IMO被實現為在一個功能ArrayUnsortedList
或簡單地執行如在您的測試類。
我認為Java環境中的測試應與JUnit一起運行。 這可能是您很快就會遇到的主題,但是如果您已經使用過JUnit,那么測試運行人員應該使用它。
在您的主要方法中,您可以將汽車添加到給定的數據類型(ArrayUnsortedList)本身。 然后,您可以將其直接傳遞給靜態方法。
另一種選擇是為ArrayUnsortedList定義一個構造函數,以接收ArrayList,並使用適當的元素創建自己的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.