Calculating the distance between 2 points using getY() and getX()

2.2k views Asked by At

I am trying to create a method to calculate the distance between two Point objects:

public class Point {

    private double x;
    private double y;

    public Point (double x, double y) {

        this.x = x;
        this.y = y;
    }

    private static void main (String[] args) {
        Point p1 = new Point(5.0,6.0);
        Point p2 = new Point(2.0,2.0);
        double distance = Math.sqrt((p1.getX() - p2.getX()) *  (p1.getX() - p2.getX()) + 
                                    (p1.getY() - p2.getY()) *  (p1.getY() - p2.getY()));
        System.out.println(distance);

    }

}

When I try to compile it I keep on getting the error saying:

Point.java:16: error: cannot find symbol
    double distance = Math.sqrt((p1.getX() - p2.getX()) *  (p1.getX() - p2.getX()) + 
                                   ^
1

There are 1 answers

0
James Dunn On BEST ANSWER

The problem is you haven't actually created your getter and setter methods (specifically the getter methods). In Java, getter and setter methods aren't automatically created for you; you have to explicitly create them yourself. So, just add the following code:

    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }

You could also just go p1.x, but it would be better practice to encapsulate the coordinates (x and y) of your Point class with getters and setters.

Also...

For your main method to work, it needs to be set to public, not private.