0

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();**
        }
    }
}
4
  • 1
    What exactly "isn't working"? Commented Feb 26, 2015 at 1:48
  • 1
    what is not working? Commented Feb 26, 2015 at 1:48
  • when using the List interface, specify what object you are storing. in your case, add <Purchase> after ArrayList Commented Feb 26, 2015 at 1:49
  • return is missing in public double totalCost(){...} Commented Feb 26, 2015 at 1:51

2 Answers 2

1

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>();
Sign up to request clarification or add additional context in comments.

Comments

1

The type information, ie the attr and method of Purchase will be erased (upcast to Object, with no self-defined attr or method) when you stored them in a ArrayList with no Generic Type, try store them like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.