Irregular Polygon Program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • slapsh0t11
    New Member
    • Oct 2009
    • 16

    Irregular Polygon Program

    Here is my assignment that I need help with:
    1. Implement a class IrregularPolygo n that contains an array list of Point2D.Double objects.

    2. The Point2D.Double class defines a point specified in double precision representing a location in (x, y) coordinate space. For example, Point2D.Double( 2.5, 3.1) constructs and initializes a point at coordinates (2.5, 3.1).

    3. Use the following declarations as a starting point for your lab work.
    Code:
    import java.awt.geom.*; // for Point2D.Double
    import java.util.ArrayList; // for ArrayList
    import gpdraw.*; // for DrawingTool
    
    public class IrregularPolygon{
    private ArrayList <Point2D.Double> myPolygon;
    
    // constructors
    public IrregularPolygon() { }
    
    // public methods
    public void add(Point2D.Double aPoint) { }
    
    public void draw() { }
    
    public double perimeter() { }
    
    public double area() { }
    }
    As far as I can tell, I am ALMOST there, but there seems to be a technicality in my main method that prevents my program from working. Here is the tester file:
    Code:
    import java.awt.geom.*;
    import java.util.Scanner;
    
    public class IrregularPolygonTester
    {
    	public static String blah = new String("Y");//is this the proper way to do this?
    	
    	public static void main(String[] args)
    	{
    		IrregularPolygon myShape = new IrregularPolygon();
    		Scanner in = new Scanner(System.in);
    		while(blah.equals("Y"))//test if user wants to keep adding points
    		{
    			System.out.print("Enter X-Coordinate: ");
    			double x = in.nextDouble();
    			System.out.print("Enter Y-Coordinate: ");
    			double y = in.nextDouble();
    			Point2D.Double myPoint = new Point2D.Double(x, y);
    			myShape.toAdd(myPoint);//this line is causing problems
    			System.out.print("Enter another point? (Y/N)");
    			blah = in.nextLine();
    			blah.toUpperCase();
    			blah.trim();
    		}
    		
    		myShape.draw();
    		System.out.println("Perimeter of figure = " + myShape.perimeter());
    		System.out.println("Area of figure = " + myShape.area());
    	}
    
    }

    And here is the regular class file:
    Code:
    import java.awt.geom.*;
    import java.util.ArrayList;
    import gpdraw.*;
    
    public class IrregularPolygon
    {
    	private ArrayList <Point2D.Double> myPolygon;
    	private double x;
    	private double y;
    	private double perim;
    	private double total;
    	private DrawingTool myPen;
    	private SketchPad myPaper;
    	
    	public IrregularPolygon()
    	{	
    		ArrayList <Point2D.Double> myPolygon = new ArrayList <Point2D.Double>();
    		x = 1;
    		y = 1;
    		perim = 0.0;
    		total = 0.0;
    		myPaper = new SketchPad(500,500);
    		myPen = new DrawingTool(myPaper);
    	}
    	
    	public void toAdd(Point2D.Double myPoint)
    	{
    		myPolygon.add(myPoint);
    	}
    	
    	public void draw()
    	{
    		myPen.up();
    		myPen.move(myPolygon.get(0).getX(), myPolygon.get(0).getY());
    		myPen.down();
    		
    		for(int i = 1; i < myPolygon.size(); i++)
    		{
    			myPen.move(myPolygon.get(i).getX(), myPolygon.get(i).getY());
    		}
    	}
    	
    	public double perimeter()
    	{
    		for(int i = 0; i < myPolygon.size(); i++)
    		{
    			perim += ((Point2D.Double)myPolygon.get(i)).distance((Point2D.Double)myPolygon.get(i + 1));
    		}
    		return perim;
    	}
    	
    	public double area()
    	{
    		for(int i = 0; i < myPolygon.size(); i++)
    		{
    			double X1 = (myPolygon.get(i).getX());
    			double Y1 = (myPolygon.get(i).getY());
    			double X2 = (myPolygon.get(i + 1).getX());
    			double Y2 = (myPolygon.get(i + 1).getY());
    			total += (X1 * Y2 - Y1 * X2);
    		}
    		return 0.5 * total;
    	}
    }

    ANY help would be greatly appreciated! If you need any additional info, please let me know! Thanks in advance!
    Last edited by Frinavale; Oct 15 '09, 03:25 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.
  • pbrockway2
    Recognized Expert New Member
    • Nov 2007
    • 151

    #2
    Originally posted by slapsh0t11
    Code:
    public static String blah = new String("Y");//is this the proper way to do this?
    It would be more straight forward to say:

    Code:
    public static String blah = "Y";
    and it would be better not to have a public static String variable at all. Since blah is only used in the main() method of IrregularPolygo nTester, declare it there. Right before it is used (ie just before the while loop).

    Code:
    myShape.toAdd(myPoint);//this line is causing problems
    Perhaps you could describe the problems this line is causing. Does it compile? If not what are the compiler messages?

    Does the program behave in an unwanted way when you run it? If so give any exception that is reported, or describe the unwanted behaviour and the input that gives rise to it.

    Comment

    • slapsh0t11
      New Member
      • Oct 2009
      • 16

      #3
      Thank you for your reply! - still need help though!

      The program does compile, but something seems to be going on with the line I indicated in my code as well as in the toAdd method in the non-tester file.


      Here is the error message I keep receiving:

      Enter X-Coordinate: 3
      Enter Y-Coordinate: 4
      Exception in thread "main" java.lang.NullP ointerException
      at IrregularPolygo n.toAdd(Irregul arPolygon.java: 28)
      at IrregularPolygo nTester.main(Ir regularPolygonT ester.java:19)

      Comment

      • pbrockway2
        Recognized Expert New Member
        • Nov 2007
        • 151

        #4
        OK.

        So you have a "NullPointerExc eption": that means that something is null when it shouldn't be. You get these if you dereference a variable which is null (eg try and invoke a method on something that is null), or if an array variable is null and you try and access one of its elements.

        This exception occurs at line 28 of IrregularPolygo n.java

        Code:
        myPolygon.add(myPoint);

        So we have the immediate cause! myPolygon is null. [Of course it might be that add() is causeing the NulPointerExcep tion because myPoint is null. But in that case the stack trace would have started with by mentioning add()'s code.]

        Now, since myPolygon is null you have two questions to answer:

        (1) Where did you try and set the value of myPolygon?
        (2) Why did this not happen?

        Comment

        • slapsh0t11
          New Member
          • Oct 2009
          • 16

          #5
          I'm not sure I quite understand the nature of this problem or how to go about resolving it. Why does it matter if the myPolygon ArrayList is null (aka empty) if I add values to it (make it NOT null) before I try to do anything else with it? Have you been able to get this code to work?

          Again, I really appreciate all of your help!

          Comment

          • pbrockway2
            Recognized Expert New Member
            • Nov 2007
            • 151

            #6
            No - null does not mean "empty"! It's more like "nonexisten t".

            There is no actual array list (created with "new") to which myPolygon refers.

            Comment

            • slapsh0t11
              New Member
              • Oct 2009
              • 16

              #7
              Isn't this the ArrayList to which myPolygon refers?

              ArrayList <Point2D.Double > myPolygon = new ArrayList <Point2D.Double >();

              Comment

              • pbrockway2
                Recognized Expert New Member
                • Nov 2007
                • 151

                #8
                Yes - that's the answer to question 1. That's where you tried to give myPolygon a value.

                Now we need to answer question 2. How come - given that line - that when you later get to toAdd() myPolygon has no value? Hint: there is a difference in that constructor between the way you give myPolygon a value and the way in which you give all of the other member variables their values. (x, y, perim, total, myPaper and myPen)

                Comment

                • slapsh0t11
                  New Member
                  • Oct 2009
                  • 16

                  #9
                  Sorry, but that didn't help much - even though I've spent the last hour or so working on this problem. I'm still quite new to Java, so a more thorough explanation of what it is I need to do would be much appreciated!

                  Comment

                  • slapsh0t11
                    New Member
                    • Oct 2009
                    • 16

                    #10
                    So, I redid the IrregularPolygo n Class, and here's the new error message I got:
                    Enter another point? (Y/N)Exception in thread "main" java.lang.Index OutOfBoundsExce ption: Index: 1, Size: 1
                    at java.util.Array List.RangeCheck (Unknown Source)
                    at java.util.Array List.get(Unknow n Source)
                    at IrregularPolygo n.perimeter(Irr egularPolygon.j ava:47)
                    at IrregularPolygo nTester.main(Ir regularPolygonT ester.java:27)


                    Here's the slightly revised code:
                    Code:
                    import java.awt.geom.*;
                    import java.util.ArrayList;
                    import gpdraw.*;
                    
                    public class IrregularPolygon
                    {
                    	private ArrayList <Point2D.Double> myPolygon = new ArrayList <Point2D.Double>();//this is what I changed
                    	private double x;
                    	private double y;
                    	private double perim;
                    	private double total;
                    	private DrawingTool myPen;
                    	private SketchPad myPaper;
                    	
                    	public IrregularPolygon()
                    	{	
                    		//ArrayList <Point2D.Double> myPolygon = new ArrayList <Point2D.Double>();
                    		x = 1;
                    		y = 1;
                    		perim = 0.0;
                    		total = 0.0;
                    		myPaper = new SketchPad(500,500);
                    		myPen = new DrawingTool(myPaper);
                    	}
                    	
                    	public void toAdd(Point2D.Double aPoint)
                    	{
                    		myPolygon.add(aPoint);
                    	}
                    	
                    	public void draw()
                    	{
                    		myPen.up();
                    		myPen.move(myPolygon.get(0).getX(), myPolygon.get(0).getY());
                    		myPen.down();
                    		
                    		for(int i = 1; i < myPolygon.size(); i++)
                    		{
                    			myPen.move(myPolygon.get(i).getX(), myPolygon.get(i).getY());
                    		}
                    	}
                    	
                    	public double perimeter()
                    	{
                    		for(int i = 0; i < myPolygon.size(); i++)
                    		{
                    			perim += ((Point2D.Double)myPolygon.get(i)).distance((Point2D.Double)myPolygon.get(i + 1));
                    		}
                    		return perim;
                    	}
                    	
                    	public double area()
                    	{
                    		for(int i = 0; i < myPolygon.size(); i++)
                    		{
                    			double X1 = (myPolygon.get(i).getX());
                    			double Y1 = (myPolygon.get(i).getY());
                    			double X2 = (myPolygon.get(i + 1).getX());
                    			double Y2 = (myPolygon.get(i + 1).getY());
                    			total += (X1 * Y2 - Y1 * X2);
                    		}
                    		return 0.5 * total;
                    	}
                    }
                    Last edited by Frinavale; Oct 15 '09, 03:27 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

                    Comment

                    • pbrockway2
                      Recognized Expert New Member
                      • Nov 2007
                      • 151

                      #11
                      Use this:

                      Code:
                      public IrregularPolygon()
                      {
                          myPolygon = new ArrayList <Point2D.Double>();
                          x = 1;
                          y = 1;
                          perim = 0.0;
                          total = 0.0;
                          myPaper = new SketchPad(500,500);
                          myPen = new DrawingTool(myPaper);
                      }
                      Do you see the difference? Do you see why the myPolygon used in the toAdd() method will now have a value?

                      Comment

                      • pbrockway2
                        Recognized Expert New Member
                        • Nov 2007
                        • 151

                        #12
                        Our posts crossed! Your revised version does much the same thing as what I posted. Make sure you understand why you don't, now, get the error in the toAdd() method.

                        Comment

                        • pbrockway2
                          Recognized Expert New Member
                          • Nov 2007
                          • 151

                          #13
                          On to the ArrayIndexOutOf BoundsException ...

                          You will get this one if an array is access at some index value that is too small (ie <0) or too big (ie >= the length of the array).

                          The stack trace tells you that this is occurring deep inside Java's ArrayList code. What you are really interested in is what in your code triggered this. You find that out by reading the stack trace from the top until you find a reference to your code.

                          In this case it is "at IrregularPolygo n.perimeter(Irr egularPolygon.j ava:47)". On this line you are accessing an array (or ArrayList) position that doesn't make sense (ie is too big or too small).

                          Code:
                          for(int i = 0; i < myPolygon.size(); i++)
                          {
                          perim += ((Point2D.Double)myPolygon.get(i)).distance((Point 2D.Double)myPolygon.get(i + 1));
                          }
                          i goes from zero (which is the first vertex of the polygon) up to myPolygon.size( )-1 which is the last vertex. Now ask yourself: if i is the last vertex of the polygon what is the expression myPolygon.get(i + 1) supposed to mean?

                          Comment

                          • slapsh0t11
                            New Member
                            • Oct 2009
                            • 16

                            #14
                            Thank you so much!! The program runs correctly now, with the exception of the area calculation...c ould you take a look at that algorithm for me?

                            Here's what it actually is:
                            0.5(X0*Y1 + X1*Y2 + ... + XN-1*Y0 - Y0*X1 - Y1*X2 - ... - YN-1*X0)

                            Can you check my area() method to see what might be giving me the incorrect output? I can't quite see what's wrong...maybe another set of eyes will help.

                            Here's that method in my program:
                            Code:
                            	public double area()
                            	{
                            		for(int i = 0; i < myPolygon.size()-1; i++)
                            		{
                            			double X1 = (myPolygon.get(i).getX());
                            			double Y1 = (myPolygon.get(i).getY());
                            			double X2 = (myPolygon.get(i + 1).getX());
                            			double Y2 = (myPolygon.get(i + 1).getY());
                            			total += (X1 * Y2 - Y1 * X2);
                            		}
                            		return 0.5 * total;
                            	}
                            Last edited by Frinavale; Oct 15 '09, 03:27 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

                            Comment

                            • pbrockway2
                              Recognized Expert New Member
                              • Nov 2007
                              • 151

                              #15
                              A picture might help. The following is a polygon with n sides. It doesn't "join up", but you didn't say it has to and that doesn't affect this problem.

                              Code:
                              0   1   2   3                      n-1  (array size is n)
                              *---*---*---*---*---*---*---*---*---*

                              How many ___ sides need to be added up to find the perimeter?

                              Comment

                              Working...