0

I've been trying to add an average cost of a petshop to the 6th slot of my table and I can't get it to work. No errors appear and I'm totally lost on how to do so. Below is the method that calculates the average cost of pets in a shop.

public String getcalculatePetshopAverage(String shop)
        {
            ArrayList<Pets> petshopPets = new ArrayList<Pets>();
            ArrayList<Pets> petsList = new ArrayList<Pets>();

            petsList.addAll(dogs);
            petsList.addAll(fishes);


            for(Pets pet : petsList)
            {
               if(pet != null && pet.getShop().equals(shop)) 
               {
                   petshopPets.add(pet);
               }
            }

            double totalAverage = 0;
            int i = 0;
            for(Pets pet : petshopPets)
            {
               i++;
               totalAverage = totalAverage + pet.getPrice();
            }
            System.out.println("There are "+i+" pets in here");



            this.averagecost = totalAverage;
            System.out.println(""+this.averagecost);

            return String.format("%.2f",totalAverage/i);


        }

Below is part of the code for the table I'm displaying in the GUI. I've tried calling the method with the name of a petshop but whenever I run the GUI for my application, in the 6th section of the table I can only see NaN.

@Override
public Object getValueAt(int rowIndex, int columnIndex) 
{
    Pets pets = petshops.get(rowIndex);

    switch (columnIndex)
    {
        case 0:
            return pets.getShop();
        case 1:
            return pets.getType();
        case 2: 
            return pets.getPrice();
        case 3:
            return pets.getDateAcquired();
        case 4:
            return pets.getNotes();
        case 5:
            return pets.getcalculatePetshopAverage(pets.getShop());

    }
    return null;

}

I'm still quite new to Java and I have no idea how to add the average cost to my table, I'd greatly appreciate some help.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

0 Answers0