We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Local variable may not have been initialized
Page Index Toggle Pages: 1
Local variable may not have been initialized (Read 1189 times)
Local variable may not have been initialized
Feb 6th, 2009, 5:16pm
 
I am trying to run the code as shown below here. I want to use the coordinates of the second node as the coordinates for the first node of the second line, etc etc.
Though I get the error 'Local variable nodeDG2 may not have been initialized".

What causes this, and how can I do this in the right way?
Thanks...


Code:
       Node nodeDG1, nodeDG2;
       for (int k=0; k<linesCopy.size(); k++) {
         L = (Line) linesCopy.get(k);
         println("Line["+L.ID1+"]["+L.ID2+"] has angle "+L.getAnglePG());
         //nodeDG1 = new Node(L.x1, L.y1, L.ID1);
         if (k==0){
           nodeDG1 = new Node(L.x1, L.y1, L.ID1);
         } else {
           println("nodeDG2 X = "+nodeDG2.x);
             nodeDG1 = new Node(nodeDG2.x, nodeDG2.y, L.ID1);
           }
         float dx = sin(L.getAnglePG())*L.getLengthPG();
         float dy = cos(L.getAnglePG())*L.getLengthPG();
         println("x1 of the line is "+L.x1+" and the x2 of the line is "+(L.x1+dx));
         nodeDG2 = new Node( (nodeDG1.x + dx), (nodeDG1.y + dy), L.ID2 );
         linesDG.add(new Line(L.ID1, L.ID2, nodeDG1.x, nodeDG1.y, nodeDG2.x, nodeDG2.y));
}
Re: Local variable may not have been initialized
Reply #1 - Feb 6th, 2009, 5:35pm
 
As said, you try to use an object that might have not been initialized...
When you declare an object at class level, it is automatically set at null. But if you declare it as local variable, it is undefined.
The workaround is simple: init the variables when declaring them (or before using them):
Node nodeDG1 = null, nodeDG2 = null;
Now, you can have instead a NullPointerException if you use the var before setting it...
Re: Local variable may not have been initialized
Reply #2 - Feb 6th, 2009, 5:38pm
 
Thanks, works as a charm!
And about NPE: I understand, and already got that problem a few times before, so I know it by now Wink
but thanks anyway ofcourse!
Page Index Toggle Pages: 1