• 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

Nested loops not working propertly

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The code below is a (simplified version of) nested loop , used to init a 2d array of Pixel objects:
(it is inside a method with two parameters - int height and int width. screen is already declared before)



However, this code (called with width and height both equal to 10) only inits 9 Objects in first row. If i change the > and < to >= and <=, it results in index out of bounds exception. What is happening here??
 
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

If height and width are 10, then you get indices 0 through 9. Do you have only nine elements or ten, because the first is in element zero?
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Never be afraid to write code to test your beliefs. It should be trivial to pull this into a new, stand alone program, and try it out. You can include some additional println statements. I's suggest something like on line 10:

System.out.println("Creating pixel at " + tempheight + ", " + width + "." );

you could also create a new counter outside the loop and increment it each time you create a new pixel, and print it's value as well - either as you go, or when your done with both loops have a "i created X objects in total".
 
Philip Johns
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yup, just reealized my mistake - i never reset the tempwidth variable to 0. Thank you for your help!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic