이 프로그램은 ArrayList에 저장된 점을 사용하여 다각형을 그려야합니다. 코드를 다시 확인하고 드라이버를 사용하고 있지만 프로그램을 실행하려고하면 프로그램을 드로잉 할 때 사용할 좌표를 추가하려고 할 때 NullPointerException
이 표시됩니다.Null 포인터 예외 다각형 스케치
import java.awt.geom.*;
import java.util.ArrayList;
import gpdraw.*;
public class IrregularPolygon
{
private ArrayList <Point2D.Double> myPolygon;
DrawingTool myPen;
SketchPad myPaper;
double dblPerimeter;
double dblSegment;
double dblArea;
public IrregularPolygon()//Creating the sketchpad and pen
{
myPaper = new SketchPad(500,500);
myPen = new DrawingTool(myPaper);
}
public void add(Point2D.Double aPoint)//Adds to the array
{
myPolygon.add(aPoint);// This is where the problem is I think, I don't know what to do
}
public void draw()//This method draws the polygon
{
for(int x = 0; x < myPolygon.size() - 1 ; x++)
{
myPen.down();
myPen.move(myPolygon.get(x).getX(),myPolygon.get(x).getY());
myPen.up();
}
}
public double perimeter()//This method finds the perimeter
{
for(int x = 0; x < myPolygon.size() - 1; x++)
{
dblPerimeter += myPolygon.get(x).distance(myPolygon.get(x+1));
}
return dblPerimeter;
}
public double area()//This method finds the area
{
for(int x = 0; x < myPolygon.size() - 1; x++)
{
double X1 = (myPolygon.get(x).getX());
double Y1 = (myPolygon.get(x).getY());
double X2 = (myPolygon.get(x + 1).getX());
double Y2 = (myPolygon.get(x + 1).getY());
dblArea += (X1 * Y2 - Y1 * X2);
}
return dblArea;
}
}
및 프로그램이 드라이버에서 실행됩니다 : 당신의 myPolygon
가 null이기 때문에 이런 일이
import java.util.*;
import java.awt.geom.Point2D;
public class IrregularPolygonDriver
{
static boolean blnReadyToDraw = false;
static Scanner in = new Scanner(System.in);
public static void main(String[]args)
{
int num;
IrregularPolygon poly = new IrregularPolygon();
while(blnReadyToDraw == false)
{
System.out.println("Would you like to add a point, find the perimeter, or calculate the area?");
System.out.println("To add a point, enter 1; to find the perimeter, enter 2; to find the area, enter 3");
num = in.nextInt();
if(num == 1)
{
double dblNum1;
double dblNum2;
Point2D.Double dblNumber;
System.out.println("Enter an x value and a y value: ");
dblNum1 = in.nextDouble();
dblNum2 = in.nextDouble();
dblNumber = new Point2D.Double(dblNum1,dblNum2);
poly.add(dblNumber);
System.out.println("Keep adding points until you are done drawing the figure.");
}
else if(num == 2)
{
poly.perimeter();
}
else if(num == 3)
{
poly.area();
}
else
{
blnReadyToDraw = true;
System.out.println("Preparing to Draw");
}
}
poly.draw();
}
}
어떤 라인이 NPE를 던집니까? –
myPolygon.add (aPoint); – Zak
아주 쉬운 것들, NPE는 뭔가 초기화하지 않았다는 것을 의미합니다. 이 경우 ArrayList를 정의하지 않았습니다. –