Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'ve been having some trouble with this for awhile now. So we\'ve been assigned

ID: 3633740 • Letter: I

Question

I've been having some trouble with this for awhile now. So we've been assigned to create a class in java called Line that essentially represents a line segment between two points.

To construct this, the following methods must be used and filled to create the new class Line, some of which I have already done (P.S. All of this will be tested by a java file I was given called LineTest.java, so creating a test case for me is not necessary):

public class Line{

private int x1;
private int y1;
private int x2;
private int y2;
private Point p1;
private Point p2;

public Line(Point p1, Point p2){
this.p1 = p1;
this.p2 = p2;
}

public Point getP1(){
return p1;
}

public Point getP2(){
return p2;
}

public String toString(){
return "(" + p1.x + "," + p1.y + ")"+ "," + "(" + p2.x + "," + p2.y +")";
}

public double getSlope(){
// Needs to be filled with code that will return the slope
}

public Line(int x1, int y1, int x2, int y2){

this.p1 = new Point (x1, y1);
this.p2 = new Point (x2, y2);
}

public boolean equals (Object j){
// Needs to be filled with code that returns whether the given other Object is a Line with the same endpoints as this Line.
}
}

So essentially, all I really need is the getSlope and equals method to finish my class. Also, we needed this code to throw some kind of exception whenever configuring the slope if the denominator is 0 and the slope is undefined.

Thanks for any help...

Explanation / Answer

That's fairly easy. Here are the two methods. public boolean equals (Object j){ Line compare; if(j instanceof Line){ compare=(Line)j; } else return false; if(compare.p1.x==p1.x&&compare.p2.x==p2.x&&compare.p1.y==p1.y&&compare.p2.y==p2.y) return true; return false; } public double getSlope(){ double slope; try{ slope=(p2.y-p1.y)/(p2.x-p1.x); //(y2-y1)/(x2-x1) } catch(ArithmeticException e){ System.out.println("denominator is zero, line is parallel to the y axis. Returning -1"); slope=-1; } return slope; }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote