This week's book giveaway is in the Security forum.
We're giving away four copies of Securing DevOps and have Julien Vehent on-line!
See this thread for details.
Win a copy of Securing DevOps this week in the Security forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Enhanced for loop  RSS feed

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

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++)
System.out.println(loc[cell]);

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

cheers

Andy
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 24
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys...much appreciated
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!