繁体   English   中英

遍历对象的数组列表

[英]Iterating through an arraylist of objects

我正在一个项目中进行工作,该项目具有一个名为Items的类和一个名为totals的方法,该方法可以计算Items对象数组的总计。 由于某种原因,它看不到项目,我知道我缺少一些简单或明显的内容,但我无法弄清楚。 蚂蚁的帮助将不胜感激。

 public void totals(){

    int index=0;
   for (Iterator it = items.iterator(); it.hasNext();) {
       Items i = it.next();
       double itotal;
        itotal = items.get(index).Items.getTotal();
   }
}

这是Items类

public class Items {
 public String name;//instance variable for item name
 public int number;//instance variable for number of item
 public double price;//instance variable for unit price
 public double total;//instance variable for total
  Items(String name,int number,double price){
    this.name=name;
    this.number=number;
    this.price=price;
    total=number*price;
}
public void setName(String name){
     this.name=name;
 }
 public void setNumber(int number){
     this.number=number;
 }
 public void setPrice(double price){
     this.price=price;
 }
 public void setTotal(){
     total=number*price;
 }
 public String getName(){
     return name;
 }
 public int getNumber(){
     return number;
 }
 public double getTotal(){
     return total;
 }
 public double getPrice(){
     return price;
 }

先谢谢您的帮助。

基本上有两个缺陷:

  1. 您永远不会递增itotal变量,并且在循环内声明它
  2. 您永远不会在当前迭代中访问变量i

而且,您的totals方法是否应该返回某些内容(例如itotal )?

我认为,迭代该项目数组的正确方法是

public double totals(){
    double itotal = 0.0;    //#A
    for (Iterator<Items> it = items.iterator(); it.hasNext();) {   //#B
       Items i = it.next();   //#C
       itotal += i.getTotal(); //#D
    }
    return itotal; //#E
}

基本上:

  • #A在这里初始化itotal变量(循环外),该变量将包含所有项目的总计
  • #B您开始遍历所有项目
  • #C您得到数组中的下一项
  • #D您将总计与当前项目的总计相加
  • #E您返回总计

这里有许多潜在的问题。

在for循环中,您声明Items i ,但从不使用它。 也许it = it.next()应该是for循环的一部分?

您调用items.get(index) ,但index始终为0。您可能想在这里使用it

您声明了double itotal ,并在for循环中分配了它,因此在每次迭代中都将其覆盖。 也许您想在循环外使用初始值声明它,然后在循环内递增它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM