Hey guys,
So basically I need to use a for-each loop to run through an ArrayList of animals in my "zoo," and make them print out their methods (roam(), eat(), etc).
I've used a for loop before, but never with an ArrayList.
Any suggestions?
Thanks!
Printable View
Hey guys,
So basically I need to use a for-each loop to run through an ArrayList of animals in my "zoo," and make them print out their methods (roam(), eat(), etc).
I've used a for loop before, but never with an ArrayList.
Any suggestions?
Thanks!
Oh and I also need to include an instance of keyword at some point during this. Can I work this code into the for loop, or do I just insert it after?
Code:
if (animal instance of Pet) {
System.out.println(beFriendly);
}
Use a for-each loop. If you know how to use a for-each loop then you know how to use it with an ArrayList.
Or use a normal for loop and call get method of ArrayList.
You would need to place the if statement inside the for loop so you can apply it to each Animal in the List.
So far I have:
Code:
Animal animal = new Animal();
for (Animal animal: zooAnimals) {
// this is the line I'm not sure of how to advance through the array list
int i = 0; i <= zooAnimals.size(); i++
System.out.println(roam);
if (animal instance of Pet) {
System.out.println(play);
}
}
for (Animal animal: zooAnimals) {
Above is a for-each loop.
int i = 0; i <= zooAnimals.size(); i++
Above is a normal for loop (missing the for keyword).
Use one or the other. Don't try to jam both together. The for-each loop advances through the list for you. Each time around the loop the next Animal object in the List is assigned to the animal variable (btw you do not need to declare the variable before the loop. In fact you should probably get a compiler error).
Okay thanks! That definitely clears things up for me