Alright so my program is supposed draw a rectangle automatically based on the coordinates (X, Y, Width, Length) that the user types in. When I run my program, i get an Exception in thread main error.
Here is the exact error:
Exception in thread "main" java.lang.NullPointerException
at rectangle.draw(rectangle.java:31)
at rectangle.main(rectangle.java:52)
Please tell me what I’m doing wrong!
Thanks!
Code: `import gpdraw.*;
import java.util.Scanner;
public class rectangle {
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();
}
}
`
Line 51: picture.draw();
Line 31: myPencil.up();
You never assign a value to the
myPencilfield, so it will have the default value ofnull. When you then try to dereference it here:… that will throw an exception.
Presumably you meant to give
myPencila value, e.g.… or perhaps do so in the constructor?