0

I read most of the other things on SO and I couldn't seem to find an answer.

  1. Don't know how to write an add method. I'm getting a StackOverflowError. It seems to run infinitely which I am not sure why.
  2. Also, just wanted to confirm that it is possible to write a print function that prints out everything in arraylist myPolygon right?
class IrregularPolygon{
    private ArrayList <Point2D.Double> myPolygon;

   // constructors
   public IrregularPolygon() { }

   // public methods
   public void add(Point2D.Double aPoint) { 
       //System.out.println("in");
       this.add(aPoint);
       System.out.println("finished");

//     for (Point2D.Double number : myPolygon) {
//         System.out.println("Number = " + aPoint);
//     }  
   }
}


public class App{
    public static void main(String[] args){
        IrregularPolygon polygon = new IrregularPolygon();
        Point2D.Double point = new Point2D.Double(1.2, 2.3);
        System.out.println(point);
        polygon.add(point);   

    } // main   
} // class
0

1 Answer 1

2

Calling this.add(aPoint) in add is a recursive call. This method calls itself, and there is no base case, so this results in a StackOverflowError once it recurses deeply enough.

It looks like you want to add it to the ArrayList, so change

this.add(aPoint);

to

myPolygon.add(aPoint);

In addition, you never initialized myPolygon, so it's null. Initialize it:

private ArrayList <Point2D.Double> myPolygon = new ArrayList<>();
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! i tried but now i'm getting: Exception in thread "main" java.lang.NullPointerException on the polygon.add(point); I can't figure out where the bad reference is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.