I need to implement the method intersection(Line) in class Line. It must return a Point of intersection of two lines.
Note that lines are defined by linear equations: y = k * x + b. Line constructor takes k and b coefficients as parameters.
If lines coincide or do not intersect, the method must return null. It may seem surprising that we use int for arguments and fields of coordinates. The point is that using double will bring some extra complexity we want to avoid for this basic exercise. All tests are selected in to induce calculations without remainders.
You may check your result in class Main.
Example
public class Main {
public static void main(String[] args) {
Line line1 = new Line(1,1);
Line line2 = new Line(-1,3);
System.out.println(line1.intersection(line2));
}
}
This is the class where I implement the solution:
public class Line {
public int b2;
public int b1;
public int k1;
public int k2;
public Line(int k, int b) {
this.k1 = k;
this.k2 = k;
this.b1 = b;
this.b2 = b;
}
public Point intersection(Line other) {
int x = (other.b2 - b1) / (k1 - other.k2);
int y = k1 * x + b1;
return new Point(x, y);
}
}
This is the Point class:
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%d;%d)", x, y);
}
}
And last class, which is Main class:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int k1 = scanner.nextInt();
int b1 = scanner.nextInt();
int k2 = scanner.nextInt();
int b2 = scanner.nextInt();
Line line1 = new Line(k1,b1);
Line line2 = new Line(k2,b2);
System.out.println("result is " + line1.intersection(line2));
}
}
This are my tests:
"1,2,2,1, result (1;3)",
"1,0,2,0, result (0;0)",
"4,3,1,3, result (0;3)",
They are correct.
What I don't know how to do is for the time when the lines coincide or do not intersect, the method must return null.
If I run my code with this examples "0,0,0,0", "1,1,1,1" and "3,-9,3,-9", I get "Exception in thread "main" java.lang.ArithmeticException: / by zero".
How can I do that?
What I have tried:
What I don't know how to do is for the time when the lines coincide or do not intersect, the method must return null.
If I run my code with this examples "0,0,0,0", "1,1,1,1" and "3,-9,3,-9", I get "Exception in thread "main" java.lang.ArithmeticException: / by zero".
I tried to put a condition to return null in case all are equal:
<pre lang="Java">
If(k1 == k2 && b1 == b2){
return null;
But still don't work and get null everytime.
How can I do that to put a condition when I have this examples:"0,0,0,0", "1,1,1,1" and "3,-9,3,-9" ?