• 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

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: 7113
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: 13073
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!
 
Happily living in the valley of the dried frogs with a few tiny ads.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic