Results 1 to 3 of 3
Thread: Distance formula
 07092013, 02:24 AM #1Member
 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((x2x1)(x2x1) + (y2y1)(y2y1)); } }
Lines 2728 are intentionally spaced like that as otherwise line 28 gets cut off.
 07092013, 02:42 AM #2Member
 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((x2x1)*(x2x1) + (y2y1)*(y2y1));Last edited by Krock999; 07092013 at 02:51 AM.
 07092013, 03:35 AM #3Senior Member
 Join Date
 Jan 2013
 Location
 Northern Virginia, United States
 Posts
 5,436
 Rep Power
 9
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,
JimThe Java^{TM} Tutorials  SSCCE  Java Naming Conventions
Poor planning on your part does not constitute an emergency on my part
Similar Threads

Distance Formula and Random numbers code
By granslime in forum New To JavaReplies: 10Last Post: 09262013, 07:27 PM 
Draw circle that can't go further than certain distance
By timdeweert in forum New To JavaReplies: 1Last Post: 04072012, 03:23 PM 
Distance Between Two Points
By HSKrustofsky in forum New To JavaReplies: 6Last Post: 09082011, 06:23 AM
Bookmarks