Write a Java program that calculates the distance between tw
Write a Java program that calculates the distance between two points when a user types the coordinates.
Solution
DistBetPoints.java
import java.util.Scanner;//package for keyboard inputting
//distance = square root of [(a2-a1)squared + (b2-b1)squared]
public class DistBetPoints
{//main class
static double distance(double a1, double b1, double a2, double b2)
{
return Math.sqrt((a2-a1)*(a2-a1) + (b2-b1)*(b2-b1));
}
public static void main(String[] args)
{ //main function
double a2, a1, b2, b1;
double distance;
Scanner scan = new Scanner (System.in);
System.out.println(\"Enter the x coordinate for point 1: \");
a1 = scan.nextDouble();//keyboard inputting
System.out.println(\"Enter the y coordinate for point 1: \");
b1 = scan.nextDouble();//keyboard inputting
System.out.println(\"Enter the x coordinate for point 2: \");
a2 = scan.nextDouble();//keyboard inputting
System.out.println(\"Enter the y coordinate for point 2: \");
b2 = scan.nextDouble();//keyboard inputting
distance = distance(a1,b1,a2,b2);//calling function
System.out.println(\"The distance between the two points is \" + distance + \" .\");
}
}
output
Enter the x coordinate for point 1:
0
Enter the y coordinate for point 1:
0
Enter the x coordinate for point 2:
2
Enter the y coordinate for point 2:
2
The distance between the two points is 2.8284271247461903 .
