Homework problem:
Add the following constructor to your Line class: public Line(int x1, int y1, int x2, int y2) Constructs the new line that contains the two given points.
My code:
Main Class:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter x1: ");
int x01 = scan.nextInt();
System.out.println("Enter y1: ");
int y01 = scan.nextInt();
System.out.println("Enter x2: ");
int x02 = scan.nextInt();
System.out.println("Enter y2: ");
int y02 = scan.nextInt();
Line object2 = new Line(x01, y01, x02, y02);
System.out.println(object2);
Point Class:
private int x;
private int y;
private static int count = 0;
public Point(int x, int y){
this.x = x;
this.y = y;
count++;
}
public Point(double x, int y){
this.x = (int)x;
this.y = y;
count++;
}
public Point(){
this(0,0);
}
public String toString(){
return "(" + x + ", " + y + ")";
}
public int getX(){
return x;
}
public void setX(int newX){
x = newX;
}
public int getY(){
return y;
}
public void setY(int newY){
y = newY;
}
Line Class:
class Line {
Point p1;
Point p2;
public Line(Point p1, Point p2) {
this.p1=p1;
this.p2=p2;
}
public Line(int x1, int y1, int x2, int y2) {
Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
}
public Point getP1() {
return p1;
}
public Point getP2() {
return p2;
}
public String toString() {
return "Line points [ (" +p1.getX() + ", " + p1.getY() + ") , ("+p2.getX() + ", " + p2.getY() + ")]";
}
However, I am still receiving a Null Pointer Exception :
Exception in thread "main" java.lang.NullPointerException
at assignement05.Line.toString(Line.java:30)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at assignement05.Assignement05.main(Assignement05.java:29)
C:\Users\18567\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 4 seconds)
Instead I should receive
Line Points [ ( x1, y1 ) , (x2, y2) ]
as my output. What is the issue here?