[英]Calling methods from objects stored in an arraylist
I was wondering why this isn't working. 我想知道为什么这不起作用。 I looked at another post that suggested the method I used for calling methods from Objects stored in an array but it doesn't seem to be working.
我看了另一篇文章,提出了我用来从存储在数组中的对象中调用方法的方法,但它似乎不起作用。 I should clarify.
我应该澄清。 I am referring to the
printPurchases
and totalCost
methods. 我指的是
printPurchases
和totalCost
方法。 More specifically how they don't seem to be allowing me to call from the Purchase
object at index i
, but instead appear to be calling from the get(i)
part. 更具体地说,它们似乎不允许我从索引为
i
的Purchase
对象调用,而是似乎从get(i)
部分调用。 It is highlighted in red in my eclipse application. 在我的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();**
}
}
}
Your return statement should have a space in between return
and ""
. 您的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()
is suppose to return a double
. public double totalCost()
假定返回double
。 You aren't returning a double
. 您不会返回
double
。
public double totalCost(){
total=0;
for(int i=0; i<purchases.size(); i++){
total = total+purchases.get(i).getCost();
}
return total;
}
Also, as said in the comments, specify what the ArrayList
is to be filled with, by using: 另外,如注释中所述,通过使用以下命令指定要填充的
ArrayList
:
private ArrayList<Purchase> = new ArrayList<Purchase>();
当您将类型信息(即Purchase
属性和方法)存储在没有泛型的ArrayList
时,其类型信息(即Purchase
的属性和方法)将被删除(上载至Object
,没有自定义的属性或方法),请尝试按以下方式存储它们:
private ArrayList<Purchase> purchases = new ArrayList<>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.