Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Nested loops not working propertly  RSS feed

 
Philip Johns
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • 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??
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • 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?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Yup, just reealized my mistake - i never reset the tempwidth variable to 0. Thank you for your help!
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!