Here's a function that will calculate distance for you:
public double getDistance(double x1, double y1, double x2, double y2){
double dx = x1-x2;
double dy = y1-y2;
return Math.sqrt(dx * dx + dy * dy);
}
The ^
character is not a valid way to raise a number to a power in java. Here's a link to valid operators in Java.
Also you must reference the static square root function, Math.sqrt, to calculate the root of a number.
I recommend you use a utility function for calculations like this as they're more difficult to read than an well named function (like the one given here.)
Edit:
In comments, Ted suggested using Math.hypot instead of Math.sqrt if you are using java 1.5 or better. The function then, would look like this:
public double getDistance(double x1, double y1, double x2, double y2){
double dx = x1-x2;
double dy = y1-y2;
return Math.hypot(dx, dy);
}
If you are using Java 1.5 or better, this is a better solution because hypot prevents overflow or underflow in computing the square of dx
and dy
.