java - Iterating through an arraylist of objects -


i working on project has class called items , method called totals calculates grand total array of items objects. reason cant see items, know missing simple or obvious cant figure out. ant appreciated.

 public void totals(){      int index=0;    (iterator = items.iterator(); it.hasnext();) {        items = it.next();        double itotal;         itotal = items.get(index).items.gettotal();    } } 

and here items class

public class items {  public string name;//instance variable item name  public int number;//instance variable number of item  public double price;//instance variable unit price  public double total;//instance variable 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;  } 

thanks in advance help.

basically, there 2 flaws:

  1. you never increment itotal variable , it's declared inside loop
  2. you never access variable i in current iteration

and also, shouldn't totals method return (like itotal)?

the way see it, proper way of iterating on items array

public double totals(){     double itotal = 0.0;    //#a     (iterator<items> = items.iterator(); it.hasnext();) {   //#b        items = it.next();   //#c        itotal += i.gettotal(); //#d     }     return itotal; //#e } 

basically:

  • #a here initialize itotal variable (outside of loop) contain grand total items
  • #b start iterating on items
  • #c next item in array
  • #d increment grand total current item's total
  • #e return grand total

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -