如何从我的 carList 中获取总价?

How do I get the total price from my carList?

我正在创建一个名为 Car 的 class,其中包含一个名为 TotalPrice 的方法,它将采用 Car 的数组并计算列表的总数。我实现了一个客户端方法 totalPrice,它接受汽车列表 (ArrayUnsortedList carList) 和 returns 等于列表中汽车总成本的整数。

我坚持编写测试驱动程序,以便我可以测试我的实际 Car class 程序。

这是我的 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;
   }      
} 

这是我的试驾 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));

   }   

}

更新********

我必须使用给定的 ArrayUnsortedList。

以下是其余代码:GITHUB

更新 现在我得到的 totalPrice 是错误的?

65700 + 38950 + 84440 = 189090

但我得到 253320???

 ----jGRASP exec: java CarList

253320

 ----jGRASP: operation complete.

在您的主要方法中,您可以将汽车添加到给定数据类型 (ArrayUnsortedList) 本身。然后你可以直接将它传递给你的静态方法。

另一种方法是为 ArrayUnsortedList 定义构造函数以接收 ArrayList,并使用适当的元素创建自己的实例。

对于totalPrice函数本身的代码,我会使用ArrayUnsortedList.size()ArrayUnsortedList.getNext()来浏览列表内容。这个列表 api 很糟糕(我想是故意的),你在这里遇到一些困难是可以理解的。学会快速浏览一个 Java class,只看函数 headers 来确定哪个函数有用。

int totalPrice = 0;
for(int i=carList.size(); i>0; i--)
{
  totalPrice += carList.getNext().getPrice();
}
return totalPrice;

您会注意到我没有在循环内引用 i;那是因为 ArrayUnsortedList 没有需要索引的方法。所以我只是依靠 i 来确保我对 ArrayUnsortedList.getNext().

进行了大量调用

关于其他主题,

  • 我不认为计算汽车价格是汽车 class 的工作。 totalPrice imo 应该作为 ArrayUnsortedList 上的一个函数来实现,还是应该像在你的测试中那样简单地执行 class.

  • 我认为 Java 环境中的测试应该 运行 使用 JUnit。这可能是您很快就会遇到的主题,但如果您已经使用过 JUnit,那么您的测试 运行 工程师应该使用它。