File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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: 4544

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:
subject: Enhanced for loop
It's not a secret anymore!