Results 1 to 7 of 7
- 09-08-2011, 03:38 AM #1
Member
- Join Date
- Sep 2011
- Posts
- 18
- Rep Power
- 0
- 09-08-2011, 03:45 AM #2
Member
- Join Date
- Sep 2011
- Posts
- 18
- Rep Power
- 0
Re: How to run a for-each loop through an ArrayList?
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?
Java Code:if (animal instance of Pet) { System.out.println(beFriendly); }
- 09-08-2011, 03:45 AM #3
Re: How to run a for-each loop through an ArrayList?
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.
- 09-08-2011, 03:46 AM #4
Re: How to run a for-each loop through an ArrayList?
You would need to place the if statement inside the for loop so you can apply it to each Animal in the List.
- 09-08-2011, 04:11 AM #5
Member
- Join Date
- Sep 2011
- Posts
- 18
- Rep Power
- 0
Re: How to run a for-each loop through an ArrayList?
So far I have:
Java 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); } }
- 09-08-2011, 04:16 AM #6
Re: How to run a for-each loop through an ArrayList?
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).
- 09-08-2011, 04:18 AM #7
Member
- Join Date
- Sep 2011
- Posts
- 18
- Rep Power
- 0
Similar Threads
-
foreach loop on ArrayList<Stack<String>>
By Ciwan in forum New To JavaReplies: 21Last Post: 06-27-2011, 07:29 PM -
Problems with a loop calling data from an ArrayList.
By moriarty in forum New To JavaReplies: 30Last Post: 03-28-2010, 02:00 AM -
Iterating through ArrayList using For loop
By Java Tip in forum Java TipReplies: 0Last Post: 01-20-2008, 08:53 AM -
Iterating through ArrayList - using newly introduce for loop in Java 5.0
By Java Tip in forum Java TipReplies: 0Last Post: 11-14-2007, 03:22 PM -
Iterating through ArrayList - traditional for loop
By Java Tip in forum Java TipReplies: 0Last Post: 11-14-2007, 03:22 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks