【问题标题】:Calling methods from objects stored in an arraylist从存储在数组列表中的对象调用方法
【发布时间】:2015-04-28 06:38:00
【问题描述】:

我想知道为什么这不起作用。我查看了另一篇文章,该文章建议了我用于从存储在数组中的对象调用方法的方法,但它似乎不起作用。我应该澄清一下。我指的是printPurchasestotalCost 方法。更具体地说,他们似乎不允许我从索引i 处的Purchase 对象调用,而是似乎从get(i) 部分调用。它在我的 Eclipse 应用程序中以红色突出显示。

public class Customer {

    private String name, address;
    double total;
    private ArrayList purchases = new ArrayList();

    public Customer(String name, String address){
        this.address=address;
        this.name=name;
    }

    public void makePurchase(Purchase purchase){
        purchases.add(purchase);
    }

    public String printPurchases(){
        for(int i=0; i<purchases.size(); i++){
            return **name+"\t"+address+purchases.get(i).toString();**
        }
        return"";
    }

    public double totalCost(){
        total=0;
        for(int i=0; i<purchases.size(); i++){
            total = **total+purchases.get(i).getCost();**
        }
    }
}

【问题讨论】:

  • 究竟是什么“不起作用”?
  • 什么不起作用?
  • 使用 List 接口时,指定要存储的对象。在您的情况下,在 ArrayList 之后添加
  • public double totalCost(){...} 中缺少返回

标签: java arrays for-loop methods arraylist


【解决方案1】:

您的 return 语句应该在 return"" 之间有一个空格。

public String printPurchases(){
    for(int i=0; i<purchases.size(); i++){
        return name+"\t"+address+purchases.get(i).toString();
    }
    return "";
}

public double totalCost() 应该返回一个double。你没有返回double

public double totalCost(){
    total=0;
    for(int i=0; i<purchases.size(); i++){
        total = total+purchases.get(i).getCost();
    }

    return total;
}

另外,如 cmets 中所述,指定 ArrayList 的内容,使用:

private ArrayList<Purchase> = new ArrayList<Purchase>();

【讨论】:

    【解决方案2】:

    类型信息,即Purchase 的attr 和方法将被删除(向上转换为Object,没有自定义 attr 或方法),当您将它们存储在@987654323 中时@ 没有 Generic 类型,尝试像这样存储它们:

    private ArrayList<Purchase> purchases = new ArrayList<>(); 
    

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 2018-10-21
      • 1970-01-01
      • 2014-05-23
      • 2012-10-08
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多