如何从Array列表中获取单个值?

时间:2013-08-02 00:11:54

标签: java arrays loops return-value

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

我的数组列表如下所示:

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。

谢谢!

2 个答案:

答案 0 :(得分: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()); 

答案 1 :(得分: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);
相关问题