I would do it like this (bottom one is shorter):
public static void calculateDogValues(){
List<Double> dogWeightList = new ArrayList<>();
double max = 0, min = 0, average = 0;
for(Pet pet: mainList){
if (pet instanceof Dog){ //add all dog weights to list
dogWeightList.add(pet.getWeight());
}
}
Collections.sort(dogWeightList); //sort the list
min = dogWeightList.get(0); //get smallest value
max = dogWeightList.get(dogWeightList.size()-1); //get highest value
for (double weight : dogWeightList) { //make sum of all weights
average += weight;
}
average = average/dogWeightList.size(); //sum/number of weights
System.out.println("Minimum weight is " + min);
System.out.println("Maximum weight is " + max);
System.out.println("Average weight is " + average);
}
Or like this without sort:
double max = 0, min = 0, average = 0, amountOfDogs = 0;
for(Pet dog: mainList){
if (dog instanceof Dog){
min = Math.min(min, dog.getWeight());
max = Math.max(max, dog.getWeight());
average += dog.getWeight();
amountOfDogs++;
}
}
average = average/amountOfDogs;
System.out.println("Minimum weight is " + min);
System.out.println("Maximum weight is " + max);
System.out.println("Average weight is " + average);
}
Also make your pet class this:
public class Pet{
private String name;
private double weight;
public String getName()
{
return name;
}
protected void setName(String newName)
{
name = newName;
}
public Pet(String petName) {
name = petName;
}
public void setWeight(double newWeight){
weight = newWeight;
}
public double getWeight(){
return weight;
}
}
There was no weight in superclass.