0

So I have an arrayList

 Dog spot = new Dog("Spot", "Lab","Blonde", Tail.OTTER,"Yes", 50, 3);
 Dog buddy = new Dog("Buddy", "Pit Bull", "Black", Tail.DOCKED,"Yes", 60, 2);
 Dog mia = new Dog ("Mia", "Pug", "Brown", Tail.RING ,"No", 70, 4);

Now the 50,60,and 70 are the weight of the dogs. I'd like to total them up without writing out lengthy, non flexible code such like:

int totalWeight = spot.weight + buddy.weight + mia.weight;

Is there a way to do that?

2 Answers 2

3
int totalWeight = 0;
for (final Dog dog : dogs) {
    totalWeight += dog.getWeight();
}
Sign up to request clarification or add additional context in comments.

2 Comments

If you wouldn't mind helping a little more how would I make it so it would only add together the dogs over 55 pounds?
Nevermind, figured it out on my own. Thank you, for the fast help!
2

Place every object in a list

List<Dog> dogs = new ArrayList<>();
dogs.add(spot);
dogs.add(buddy);
dogs.add(mia);

int result = 0;
for(Dog dog : dogs) {
 result += dog.getWeight(); 
}

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.