-1

How can I write a double slope method for a segment class?

I have two variable: p1 = x1, y1 and p2 = x2, y2.

I did this code but this is wrong:

public double slope() {
    return (double)(p2.y - p1.y)/(p1.x-p2.x);
}

Can someone tell me why is it wrong? What is the right way to write it?

Thank you!

danmullen
  • 2,556
  • 3
  • 20
  • 28
Hr0419
  • 61
  • 1
  • 3
  • 8
  • FYI: code snippets only run when someone uses Javascript. You're using Java, and that isn't supported. – Makoto Sep 25 '14 at 22:48
  • possible duplicate of [Division of integers in Java](http://stackoverflow.com/questions/7220681/division-of-integers-in-java) – Ben Sep 25 '14 at 22:49

1 Answers1

0

Depending on the type of p1, it could be a Point which takes both an x and a y coordinate.

public class Point {
    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

You'd have to use getX() and getY() to get the X and Y coordinates. You'd also have to be sure you created the point with new Point(1, 2) as well.

Also, be sure that you're getting the right cast behavior by adding parens around it and your numerator:

return ((double)(p2.getY() - p1.getY()))/(p1.getX() - p2.getX());

(Although that above seems to scream for a deltaY and deltaX method alone)

Makoto
  • 104,088
  • 27
  • 192
  • 230