This week's book giveaway is in the Cloud/Virtualizaton forum.We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

Polygon()

Vanitha Sugumaran
Ranch Hand
Posts: 356
Hi,
If I created an empty polygon and added 6 points, then when I displayed the points there were 2 zeros. why java is adding 2 extra zero's?
Here is the code:-
import java.awt.*;
import java.awt.event.*;

public class Polytest
{
static Polygon p = new Polygon();

public static void main(String[] args)
{

int[] x = p.xpoints;
int[] y = p.ypoints;
if (x == null)
{
System.out.println("X is null");
}
else
{
System.out.println("The length of the x points and y points are " + x.length + " " + y.length);
for(int i = 0; i < x.length; i++)
{
System.out.println("the value of x["+i+"]" + x[i] + " " + y[i]);
}
}

}
}
Thanks,
Vanitha

Richard Boren
Ranch Hand
Posts: 233
Hi Vanitha, I modified you code as follows and didn't get the two extra points. I believe the addPoint() is what was causing the extra points since it appends points to the poly. Don't know why two though. Hope this helps.

Vanitha Sugumaran
Ranch Hand
Posts: 356
Hi,
Thanks for your reply. In the above code we know the points, so we can straight away create x[] and y[] arrays.
But there are some cases when we have to addpoints to the polygon, so what to do in those times?
Vanitha

Manfred Leonhardt
Ranch Hand
Posts: 1492
Hi Vanitha,
Your problem comes about because you are not making use of the public variable 'npoints'. It is the one that tells you how many points exist in the polygon at any time. You are using the xpoints and ypoints arrays defined in Polygon. If you look in the code the arrays start out as length = 4 and the length is doubled everytime it has been exceeded. In your case your 5th point exceeded the limit so the xpoints and ypoints arrays were changed to be of length 8. If you had continued to add a 9th element the arrays would then be changed to length = 16!
You should make use of npoints like so.

Or just go ahead and use the constructor that Richard illustrated. By using the constructor the Polygon class creates an exact size array because it knows the number of points apriori. But if you then use addPoint you will run into the same situation that you have discussed ...
Regards,
Manfred.

Vanitha Sugumaran
Ranch Hand
Posts: 356
Hi,
Now I got the point. Thanks.
Vanitha