
Distance formula
I am trying to create a Java program that takes input for the coordinates of 2 points and then use it to calculate the distance of these two point.
Here us what I have so far. The compiler is highlighting the minus X1 part in the distance formula. I could not figure out why though.
Code:
import java.util.Scanner;
public class Distance
{
public static void main (String[] args)
{
float x1, y1, x2, y2;
Scanner in = new Scanner(System.in);
System.out.println ("Please enter x and y values for two points");
x1 = in.nextFloat();
System.out.println(" ");
x2 = in.nextFloat();
System.out.println ("Pleas enter values for y." );
y1 = in.nextFloat();
y2 = in.nextFloat();
System.out.println(" ");
System.out.println ("The coordinate of the points you have entered is
" + "(" + x1 + "," + y1 + ")" + " and " + "( " + x2 + "," + y2 + " )" );
float Distance = sqrt((x2x1)(x2x1) + (y2y1)(y2y1));
}
}
Lines 2728 are intentionally spaced like that as otherwise line 28 gets cut off.

Re: Distance formula
First, it doesn't multiply like that. Make the '*' signs on the sides. Second, your sqrt doesn't work. I am a beginner so I don't know a lot too.
Adding a:
private static float sqrt(float f) {
return 0;
}
works but is useless..
EDIT:
I think this would be the best:
double Distance = Math.sqrt((x2x1)*(x2x1) + (y2y1)*(y2y1));

Re: Distance formula
Well, as long as you are using the Math.sqrt() method you may as well use the Math.hypot() method to calculate the distance. It would probably be more accurate anyway.
And I would also recommend to use double instead of float.
Regards,
Jim