2014-10-11 132 views
-4

新手Java程序員在這裏(2周)從學校得到一份任務來創建一個Sierpinski三角形程序。JAVA:我不明白這個NullPointerException

處理繪圖的代碼已經存在,我只需創建表示頂點和三角形的對象以及劃分三角形的方法。我做了所有這些,但調用應該繪製三角形的方法給了我一個NullPointerException,我不知道是什麼導致了它。

我不能分享我的代碼,可能會導致我自動故障的過程中,但在這裏,讓我錯誤的預先寫好的方法:

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; 
} 

我敢肯定,我的getX和的getY方法正確。

感謝您對我英文不熟悉的幫助和歉意。

+1

什麼是異常棧跟蹤說?有幾件事可以爲空 - >檢查面板,三角形,a,b,c和三角形。 – brianestey 2014-10-11 16:40:17

+4

你看過[什麼是空指針異常,我該如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -我修復它) – 2014-10-11 16:41:11

回答

0

這些都是所有的事情,可以在你的代碼是空的列表:

  1. 三角
  2. 面板
  3. 一個
  4. b
  5. Ç

最佳猜測會是a,b或c是null,因此a.getX(),b.getX()或c.getX()可能是throwi ng NullPointerException

0

¿您是否在傳遞intantialize並初始化三角形對象?

喜歡的東西:

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); 

在另一方面,也許你沒有正確創建面板對象。

JPanel panel = new JPanel(); 
panel.setPreferredSize(new Dimension(800,600))