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()) +
^
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:
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
, notprivate
.