• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Enhanced for loop

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks guys...much appreciated
 
I was born with webbed fish toes. This tiny ad is my only friend:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic