aspose file tools*
The moose likes Beginning Java and the fly likes Question about a 2D array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question about a 2D array" Watch "Question about a 2D array" New topic
Author

Question about a 2D array

Ryan Davey
Greenhorn

Joined: Nov 13, 2008
Posts: 2
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
Sheriff

Joined: Sep 28, 2004
Posts: 18104
    
  39



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 ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ryan Davey
Greenhorn

Joined: Nov 13, 2008
Posts: 2
This makes sense. Thanks for the help.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

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.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about a 2D array
 
Similar Threads
Someone teach me line by line how to read this particular code
JFrame visible - all else invisible.
problem using getSize on classes in jar file
how to add scrollpane for a jpanel with null layout manager.
Problem Finding Index Value of a String in Array