aspose file tools*
The moose likes Beginning Java and the fly likes Polygon() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Polygon()" Watch "Polygon()" New topic
Author

Polygon()

Vanitha Sugumaran
Ranch Hand

Joined: Apr 11, 2001
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)
{
p.addPoint(10,20);
p.addPoint(20,40);
p.addPoint(55,65);
p.addPoint(47,50);

p.addPoint(50,67);
p.addPoint(34,34);

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

Joined: Mar 01, 2001
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

Joined: Apr 11, 2001
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

Joined: Jan 09, 2001
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

Joined: Apr 11, 2001
Posts: 356
Hi,
Now I got the point. Thanks.
Vanitha
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Polygon()