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.
Basically, there are two flaws:
itotal
variable and it's declared inside the loop 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:
itotal
variable (outside of the loop) that will contain the grand total for all items 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.