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. 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. It is highlighted in red in my eclipse application.
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 ""
.
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
. You aren't returning a 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:
private ArrayList<Purchase> = new ArrayList<Purchase>();
当您将类型信息(即Purchase
属性和方法)存储在没有泛型的ArrayList
时,其类型信息(即Purchase
的属性和方法)将被删除(上载至Object
,没有自定义的属性或方法),请尝试按以下方式存储它们:
private ArrayList<Purchase> purchases = new ArrayList<>();
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.