【问题标题】:Iterating through an arraylist of objects遍历对象的arraylist
【发布时间】:2015-07-22 17:43:23
【问题描述】:

我正在处理一个项目,该项目有一个名为 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;
 }

提前感谢您的帮助。

【问题讨论】:

  • 你能粘贴任何正在发生的错误吗? “它看不到项目”不是非常技术性或特定于问题。
  • 这是我在线程“main”java.lang.RuntimeException 中编译异常时得到的错误:无法编译的源代码 - 错误的符号类型:ReciptPrinter.ReciptPrinter 的 java.lang.Object.getTotal。 Totals(ReciptPrinter.java:52) at ReciptPrinter.ReciptPrinter.main(ReciptPrinter.java:36) Java 结果:1 IDE 给出此错误找不到符号符号:方法 getTotal() 位置:对象类型的变量项

标签: java object arraylist


【解决方案1】:

基本上有两个缺陷:

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

【讨论】:

  • 这让我更接近了,谢谢我仍然对以下行有疑问:Items i = it.next();它给出了错误“不兼容的类型:对象无法转换为项目”
  • 我的错,我已经更新了我的答案。如果您的项目列表声明为List&lt;Items&gt;,则迭代器声明可以声明为Iterator&lt;Items&gt;,并且项目将在循环中具有正确的类型。
  • 哇哦!现在我感觉自己像个菜鸟(我就是),但这让我继续前进。谢谢!
  • 很高兴你找到了自己的路;)谢谢!
【解决方案2】:

这里有很多潜在的问题。

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

您调用items.get(index),但index 始终为0。您可能希望在此处使用it

您声明 double itotal 并在 for 循环中分配它,因此它在每次迭代时都会被覆盖。也许你想在循环外用一个初始值声明它,然后在循环内增加它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 2018-08-04
    • 1970-01-01
    • 2019-04-19
    • 2016-06-04
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多