This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I have a Java class that recursively builds a 'tree' . This Java class works as I expected without problem. I am able to write out this 'tree" to the console "line by line" with proper indentation.
The problem occurs when I try to iterate through this 'tree' in the public static void main(String arg) method -- Each line in the tree is an Array. And I have to declare this Array (called titleArray in my code) non-static; otherwise, I end up with picking up the very last line of my hard-coded data.
Besides, I also have to declare the List (called recursiveTextArray in my code) non-static; otherwise, I end up with picking up the first Array that I ever build and run into endless iterations till the heap size is exhausted. Note that each element of that List is an Array object.
Then, this non-static Array and this non-static List cannot be accessed in the public static void main(String arg) method.
What should I do?
Here is my code that works without problem (the one I do not access the 'titleArray' in the main(String arg) method):
And the code below gives me the static and non-static problem:
In the lines that you have marked with "compilation error" you are trying to access non-static member variables, but you are not specifying at which object you are looking.
Remember that non-static methods always execute in the context of a current object. Static methods are class-level methods; they do not execute on a specific object. You cannot access non-static members from a static method, because there is no current object at which you're looking.
You should specify the object that you want to look at explicitly, for example: