# Thread: Distance formula

1. Member Join Date
Jul 2013
Posts
1
Rep Power
0

## 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.

Java 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((x2-x1)(x2-x1) + (y2-y1)(y2-y1));

}

}```

Lines 27-28 are intentionally spaced like that as otherwise line 28 gets cut off.  Reply With Quote

2. Member Join Date
Jul 2013
Posts
10
Rep Power
0

## 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((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
Last edited by Krock999; 07-09-2013 at 02:51 AM.  Reply With Quote

3. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
15

## 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  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•