gpt4 book ai didi

java - 遍历对象的数组列表

转载 作者:行者123 更新时间:2023-11-30 03:26:05 25 4
gpt4 key购买 nike

我正在开发一个项目,该项目有一个名为 Items 的类和一个名为 Totals 的方法,用于计算 Items 对象数组的总计。由于某种原因它看不到项目,我知道我错过了一些简单或明显的东西,但我就是无法弄清楚。 Ant 的帮助将不胜感激。

 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)吗?

在我看来,迭代该 items 数组的正确方法是

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 您返回总计

关于java - 遍历对象的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30180901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com