Explore BrainMass

Implementing Line Equations In Java

This content was STOLEN from BrainMass.com - View the original, and get the solution, here!

A line in the plane can be specified in various ways:

by giving a point (x, y) and a slope m

by giving two points (x1, y1), (x2, y2)

as an equation in slope-intercept form y = mx + b

as an equation x = a if the line is vertical

Implement a class Line with four constructors, corresponding to the four cases above. Implement methods

boolean intersects(Line other)
boolean equals(Line other)
boolean isParallel(Line other)

Use the following class as your tester class:

public class LineTester
public static void main(String[] args)
Line line1 = new Line(1, 1, 0.5);
Line line2 = new Line(1, 1, 1, 2);
Line line3 = new Line(0.5, -1);
Line line4 = new Line(1);

System.out.println("Expected: false");
System.out.println("Expected: true");
System.out.println("Expected: true");
System.out.println("Expected: false");
System.out.println("Expected: true");
System.out.println("Expected: true");
System.out.println("Expected: false");

© BrainMass Inc. brainmass.com September 22, 2018, 5:17 am ad1c9bdddf - https://brainmass.com/computer-science/java/implementing-line-equations-java-459795

Solution Preview

Please see the attachment in case something does not appear clearly here.

class Line {
double slope;
double xIntercept;
double yIntercept;

public Line(double x0, double y0, double m) {
// The line has equation y - y0 = m(x - x0)
// Then y = mx + (y0 - m*x0)
this.slope = m;
this.yIntercept = y0 - m * x0;
public Line(double x1, double y1, double x2, double y2) {
if (x1==x2) {
// The line has equation x = x1
this.slope = Double.MAX_VALUE; // slope is infinity
this.xIntercept = x1;
} else {
// The slope is m = (y2 - y1)/(x2 - ...

Solution Summary

The solution discusses implementing line equations in Java.