“线程中的异常”;“主要”;java.lang.NullPointerException错误。使用Gpdraw
好的,我的程序应该根据用户输入的坐标(X,Y,宽度,长度)自动绘制一个矩形。当我运行我的程序时,我在线程主错误中得到一个异常 下面是确切的错误:“线程中的异常”;“主要”;java.lang.NullPointerException错误。使用Gpdraw,java,exception,nullpointerexception,Java,Exception,Nullpointerexception,好的,我的程序应该根据用户输入的坐标(X,Y,宽度,长度)自动绘制一个矩形。当我运行我的程序时,我在线程主错误中得到一个异常 下面是确切的错误: Exception in thread "main" java.lang.NullPointerException at rectangle.draw(rectangle.java:31) at rectangle.main(rectangle.java:52) 请告诉我我做错了什么 谢谢 代码:`导入gpdraw.*; 导入java.util.Sc
Exception in thread "main" java.lang.NullPointerException
at rectangle.draw(rectangle.java:31)
at rectangle.main(rectangle.java:52)
请告诉我我做错了什么
谢谢
代码:`导入gpdraw.*;
导入java.util.Scanner
公共类矩形{
private static double myX;
private static double myY;
private static double myWidth;
private static double myHeight;
private DrawingTool myPencil;
private SketchPad myPaper;
public double getPerimeter(){
double perimeter;
perimeter = myWidth * 2 + myHeight * 2;
return perimeter;
}
public double Area(){
double area;
area = myHeight * myWidth;
System.out.println("Area: " + area);
return area;
}
public void draw(){
myPencil.up();
myPencil.move(myX , myY);
myPencil.down();
myPencil.move(myX + myWidth, myY);
myPencil.move(myX + myWidth, myY + myHeight);
myPencil.move(myX , myY);
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter X Value: ");
myX = input.nextInt();
System.out.println("Enter Y Value: ");
myY = input.nextInt();
System.out.println("Enter Width: ");
myWidth = input.nextInt();
System.out.println("Enter Height: ");
myHeight = input.nextInt();
rectangle picture = new rectangle();
picture.draw();
}
}
`
第51行:picture.draw();
第31行:myPencil.up() 您从不为
myPencil
字段赋值,因此它的默认值为null
。然后尝试在此处取消引用时:
myPencil.up();
。。。这将抛出一个异常
大概你是想给myPencil
一个值,例如
private DrawingTool myPencil = new Pencil();
。。。或者在构造函数中执行此操作?您需要实例化
myPencil
:
myPencil = new DrawingTool();
第31行是哪一行?第52行是什么?第31行:mypencil.up();第52行:picture.draw();你在哪里给我的铅笔赋值?在公共课上。我想我忘了抄一些。让我快速编辑一下