The moose likes Beginning Java and the fly likes Enhanced for loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Enhanced for loop" Watch "Enhanced for loop" New topic

Enhanced for loop

Andrew Hudson

Joined: Aug 18, 2011
Posts: 6

I'm a beginner and building a battleship game. I'm testing an enhanced for loop and don't understand why I'm getting an outofbounds error.

I know that I can use a normal 'for' loop to make it work ie for(int cell = 0;cell<loc.length;i++)

but why does the enhanced for loop seem to loop past the length of the array?


Matthew Brown

Joined: Apr 06, 2010
Posts: 4343

Hi Andrew, welcome to the Ranch!

It's not iterating past the end of the loop. It's taking the value in each element (which can be as high as 6, depending on the random number chosen) and using it as an index (which can only take 0-2). So there's a fair chance one of the indexes is going to be out of bounds.

What you need, to give you the equivalent of the 'normal' for loop, is simply:

One thing to remember about the enhance loop is that you don't have access to the index, only the value held in the current position of the array.
MrKamal Joshi

Joined: Jul 31, 2011
Posts: 24

Actually you are making a mistake in printing out the elements of the array loc.You have written System.out.println(loc[cell]); where cell refers to values in array loc,and cell can have value greater than 2 which is outside the bounds of array loc.You have to use System.out.println(cell); for printing out array loc elements.
Andrew Hudson

Joined: Aug 18, 2011
Posts: 6
thanks guys...much appreciated
I agree. Here's the link: http://aspose.com/file-tools
subject: Enhanced for loop
Similar Threads
How do iterate 2 list's using for-each loop(enhanced for loop)
doubt pg 340 of k&b
Question on java.util.Random
Enhanced For Loop Problem
Help in Linear Search