Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about a 2D array

 
Ryan Davey
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey there, I'm a beginner to java, of course.

Through using google to figure out problems i've noticed this site a handful to times and I've found it to be very helpful, so i figured i would register.

On to my question.

I'm trying to initialize 3 x 3 array of JPanels with nested enhanced for loops, but it's not working.



Edit: sorry for the vagueness. It doesn't seem to be working because i'm getting a null pointer exception in another part of my program. Which means that the loop doesn't even seem to be going anywhere. each panel is just ending up "null" after the loop. I'll debug this and try to see what exactly it is doing and come back with another edit or a reply if i figure it out. Sorry i didn't do this before, i only had about 5 minutes left in the class i was in.



This code works, but it looks terrible, haha, and i'm sure it's bad practice, but i'm new to programming in general, not just java. I know there's probably a more concise way to do this with for loops.


[ November 13, 2008: Message edited by: Ryan D. ]
 
Henry Wong
author
Marshal
Pie
Posts: 20992
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The panel variable is a looping variable -- it is assigned to the value of each element of the array. Setting it doesn't set the array. Setting it just changes the looping variable.

To change the array itself, you need to assign the array. And it is easier to use the other for loop.



Henry
[ November 13, 2008: Message edited by: Henry Wong ]
 
Ryan Davey
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This makes sense. Thanks for the help.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that



is legal, and would prevent you from making this mistake. Really, they should have made the loop variable final by default, IMO. But using "final" there is a good habit to get into.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic