-1

所以我正在开发这个程序,我需要对包含项目、项目数量、库存总单位和价格的数组列表进行排序。我已经这样做了,我遇到的唯一问题是我找不到通过将总单位乘以价格来获得数组列表总数的方法。

我的数组列表如下所示:

ArrayList< Inventory > a1 = new ArrayList<  >();

    a1.add(new Inventory("shoes", 1345, 134, 20.50f));
    a1.add(new Inventory("pies", 1732, 150, 3.35f));
    a1.add(new Inventory("cherries", 1143, 200, 4.40f));
    a1.add(new Inventory("shirt", 1575, 99, 10.60f));
    a1.add(new Inventory("beer", 1004, 120, 8.50f));

现在要评估总数,我尝试将其放入构造函数类中:

public float getTotal()
  {
      float total = 0.0f;

      return total += getUnit() * getPrice();  
  }

当我尝试在主类中使用它时,这是我写的:

Inventory[] array = new Inventory[a1.size()];
    Arrays.sort(a1.toArray(array));
    for (Inventory p : array)
        System.out.println(p);


    for(Inventory total: array)

    System.out.printf("The total of the Inventory is:$%.2f ", total.getTotal());

我的问题是,评估会遍历每一行并输出每一行的每一个值。我尝试了许多其他不同的 for 循环,但无法将其变为单个总值,该总值会评估整个数组列表。有人能解释一下我怎样才能把它变成一个单一的值吗?我以前做过,但是当我更改数组列表以对其进行排序时,现在我无法再次获得单个值。

哦!这是在 Netbeans for Java 中。

谢谢!

4

2 回答 2

3

这个

Inventory[] array = new Inventory[a1.size()];
Arrays.sort(a1.toArray(array));

可以通过这个实现

Collections.sort(a1)

这将对您的列表进行排序,然后您只需循环一次即可获得总数(我假设这是您想要的)

float total = 0;
for(Inventory i: a1)
{
     total += i.getTotal();
     //if you want to print for every item, otherwise remove below line
     System.out.println(i)
}
System.out.println("The total is " + total); // This will just print one line 
                                             // with the total of the entrie list

编辑由于此代码,您获得了双倍的输出

for (Inventory p : array)
    System.out.println(p);  // This prints every item in the list once

for(Inventory total: array) // And this is looping and printing again!
                            // This empty line does not matter, line below is looped
    System.out.printf("The total of the Inventory is:$%.2f ", total.getTotal()); 
于 2013-08-02T00:20:21.380 回答
1

您没有添加循环中每个“库存”的总数:

Inventory[] array = new Inventory[a1.size()];
Arrays.sort(a1.toArray(array));
float total = 0;
for (Inventory p : array)
{
    total += p.getTotal()
}
System.out.printf("The total of the Inventory is:$%.2f ", total);
于 2013-08-02T00:20:40.333 回答