I'm doing this project where I need to have this specific class structure and find the slope. I need to somehow find the slope using points 1 and 2 (p1, p2).
//file MyPoint
import java.text.DecimalFormat;
public class MyPoint {
private double x;
private double y;
public MyPoint() {
double xP = x;
double yP = y;
}
public double getX(double x) {
return x;
}
public double getY(double y) {
return y;
}
public String toString() {
DecimalFormat df_obj = new DecimalFormat("#.###");
return "(" df_obj.format(getX(x)) "," df_obj.format(getY(y)) ")";
}
}
//file MyLine
public class MyLine {
private MyPoint p1;
private MyPoint p2;
private double slope;
private double xint;
private double yint;
public MyLine(MyPoint p1, MyPoint p2) {
p1 = new MyPoint();
p2 = new MyPoint();
}
public static MyPoint getPointOne(MyPoint p1) {
return p1;
}
public static MyPoint getPointTwo(MyPoint p2) {
return p2;
}
public static double getSlope() {
double slope = //don't know what to put here in order to get the slope from p1 and p2;
return slope;
}
}
CodePudding user response:
The slope is calculated as rise/run
which means delta Y
divided by delta X
.
double slope = (p1.getY() - p2.getY())/(p1.getX() - p2.getX());
and the equation of the line is y = slope*x b
where b
is the y-intercept
(where the line crosses the y-axis
if extended that far).
double b = y - slope*x; // use either point for x,y
CodePudding user response:
A common slope calculation between 2 points would be:
slope = DeltaX / DeltaY = (x2 - x1) / (y2 - y1)
So in your getSlope() method you'd use:
double slope = (p2.getX() - p1.getX()) / (p2.getY() - p1.getY());
By the way I think there are a couple of mistakes in your code:
- your getX() and getY() don't need to have 'x' and 'y' respectively as parameters. The x and y values are inside the MyPoint class' p1 and p2 instances.
- On the other hand, the MyPoint constructor needs to receive the 'x' and 'y' parameters, in order to assign them to the inner xP and yP variables respectively.