Objective: Given two coordinates (x1, y1) and (x2, y2). Write a java program to construct a line equation that passes through the given coordinates.
Line Equation:
1 2 3 4 | Given two coordinates (x1, y1) and (x2, y2) the line equation is y - y1 = m(x - x1) where m is the slope of the line, where slope = (y2-y1)/(x2-x1) |
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public class JavaExample { static class Coordinate{ int x; int y; public Coordinate(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "["+this.x+","+this.y+"]" ; } } public static void createEquation(Coordinate c1, Coordinate c2){ System.out.println("Given coordinates: " + c1 + " and " + c2); // slope = (y2-y1)/(x2-x1) int slope = (c2.y-c1.y)/(c2.x-c1.x); // y = mx + b, b = y - mx, m = slope int b = c1.y - slope*c1.x; System.out.format("Line Equation: y = %+dx %+d", slope,b); } public static void main(String[] args) { Coordinate c1 = new Coordinate(2,2); Coordinate c2 = new Coordinate(4,12); createEquation(c1, c2); } } |
Output:
1 2 3 4 | Given coordinates: [2,2] and [4,12] Line Equation: y = +5x -8 |