Joshua Rastetter
Joshua Rastetter

Reputation: 33

Iterating through an arraylist of objects

I am working on a project that has a class called Items and a method called totals that calculates a grand total for an array of Items objects. for some reason it cant see Items, I know that I am missing something simple or obvious but I just cant figure it out. Ant help would be appreciated.

 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();
   }
}

and here is the Items class

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;
 }

Thanks in advance for the help.

Upvotes: 1

Views: 1163

Answers (2)

Val
Val

Reputation: 217544

Basically, there are two flaws:

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

And also, shouldn't your totals method return something (like itotal)?

The way I see it, the proper way of iterating over that items array is

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
}

Basically:

  • #A Here you initialize the itotal variable (outside of the loop) that will contain the grand total for all items
  • #B You start iterating over all items
  • #C You get the next item in the array
  • #D You increment the grand total with the current item's total
  • #E You return the grand total

Upvotes: 2

Jeff Ames
Jeff Ames

Reputation: 1446

There are a number of potential issues here.

In your for loop, you declare Items i, but never use it. Maybe it = it.next() should be a part of the for loop instead?

You call items.get(index), but index is always 0. You might want to use it here instead.

You declare double itotal and assign it within the for loop, so it's overwritten on each iteration. Maybe you want to declare it with an initial value outside the loop, and then increment it inside the loop.

Upvotes: 0

Related Questions