-4

newbie Java programmer here (2 weeks) got an assignment from school to create a Sierpinski triangle program.

The code that handles the drawing is already there, I just have to create objects representing the vertices and triangles and a method that divides the triangle. I did all that, but calling the method that's supposed to draw the triangles gives me a NullPointerException and I have no idea what's causing it.

I cannot share my code as that may result in me automatically failing the course, but here's the pre-written method that gives me the error:

public boolean paintTriangle(Triangle triangle) {
    int width = panel.getWidth();
    int height = panel.getHeight();
    int halfX = width/2;
    int halfY = height/2;

    Vertex2D a = triangle.getVertexA();
    Vertex2D b = triangle.getVertexB();
    Vertex2D c = triangle.getVertexC();

    int minX = width - ((int) Math.rint(halfX - Math.min(a.getX(), Math.min(b.getX(), c.getX())))); //this is where I get the nullPointerException
    int maxX = width - ((int) Math.rint(halfX - Math.max(a.getX(), Math.max(b.getX(), c.getX()))));
    int minY = (int) Math.rint(halfY - Math.min(a.getY(), Math.min(b.getY(), c.getY())));
    int maxY = (int) Math.rint(halfY - Math.max(a.getY(), Math.max(b.getY(), c.getY())));

    if (minX < 0 || maxX > width || minY < 0 || maxY > height) {
        return false;
    }
    triangles.add(triangle);
    return true;
}

I'm sure my getX and getY methods are correct.

Thanks for the help and sorry for my wonky English.

  • 1
    What's the exception stack trace say? There are a few things that can be null --> check panel, triangle, a, b, c, and triangles. – brianestey Oct 11 '14 at 16:40
  • 4
    Have you read [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Paul Samsotha Oct 11 '14 at 16:41

2 Answers2

0

These are a list of all the things that can be null in your code:

  1. triangle
  2. panel
  3. a
  4. b
  5. c

Best guess would be that a, b or c is null and therefore a.getX(), b.getX() or c.getX() could be throwing NullPointerException

Sanchit
  • 2,240
  • 4
  • 23
  • 34
0

¿Are you passing an intantialize and initialize triangle object?

Something like:

Triangle triangle = new Triangle();

Vertex2D vertexA = new Vertex2D();
vertexA.setX(x); // x and y are numeric primitives
vertexA.setY(y);

Vertex2D vertexB = new Vertex2D();
vertexB.setX(x);
vertexB.setY(y);

Vertex2D vertexC = new Vertex2D();
vertexC.setX(x);
vertexC.setY(y);

triangle.setVertexA(vertexA);
triangle.setVertexB(vertexB);
triangle.setVertexC(vertexC);

paintTriangle(triangle);

On the other hand, maybe you haven't created correctly the panel object.

JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(800,600))
Mar Millán
  • 188
  • 7