Originally Posted by
Norm
Multiply the degrees by radians/degree
Check the Math class for a method
There was a mistake in the formula. It was suppose to be arccos, not arctan. I did that by accident. I made two new classes, the first one has the fixed formula with the degrees to radian conversion, and the other is using a nested class. They yield different outputs, but the nested class one is closer to the desired output when I input the following:
Input Data:
Input the latitude of coordinate 1: 25
Input the longitude of coordinate 1: 35
Input the latitude of coordinate 2: 35.5
Input the longitude of coordinate 2: 25.5
Expected Output
The distance between those points is: 1480.0848451069087 km
import java.lang.Math;
import java.util.Scanner;
class RicMain
{
public static void main(String args[])
{
Scanner ip = new Scanner(System.in);
double x1, x2, y1, y2, a, d;
a = 6371.01; //a is the radius of the sphere.
//radius of Earth is 6371.01 km.
System.out.print("Input the latitude of coordinate 1: ");
x1 = ip.nextDouble();
System.out.print("Input the longitude of coordinate 1: ");
y1 = ip.nextDouble();
System.out.print("Input the latitude of coordinate 2: ");
x2 = ip.nextDouble();
System.out.print("Input the longitude of coordinate 2: ");
y2 = ip.nextDouble();
//x1 and x2 are the latitude (x-axis) in degrees.
//y1 and y2 are the longitude (y-axis) in degrees.
//d is the great circle distance (distance between the two points (x1, y1) and (x2, y2).
d = a * Math.acos((Math.cos(x1)*Math.cos(x2)*Math.cos(y1 - y2)) + (Math.sin(x1)*Math.sin(x2)));
System.out.println("\nThe distance between points (x1, y1) and (x2, y2) is " + Math.toRadians(d) + " km");
}
}
import java.lang.Math;
import java.util.Scanner;
class RicMain
{
public static void main(String args[])
{
Scanner ip = new Scanner(System.in);
double x1, y1, x2, y2;
System.out.print("Input the latitude of coordinate 1: ");
x1 = ip.nextDouble();
System.out.print("Input the longitude of coordinate 1: ");
y1 = ip.nextDouble();
System.out.print("Input the latitude of coordinate 2: ");
x2 = ip.nextDouble();
System.out.print("Input the longitude of coordinate 2: ");
y2 = ip.nextDouble();
//x1 and x2 are the latitude (x-axis) and measured in degrees.
//y1 and y2 are the longitude (y-axis) and measured in degrees.
System.out.println("\nThe distance between points (x1, y1) and (x2, y2) is " + d(x1, y1, x2, y2, y2) + "km");
}
//this inner class converts points to radians.
//Math.toRadians() converts degrees into radians.
public static double d(double x1, double x2, double y1, double y2, double a)
{
x1 = Math.toRadians(x1);
y1 = Math.toRadians(y1);
x2 = Math.toRadians(x2);
y2 = Math.toRadians(y2);
a = 6371.01; //radius of Earth is 6371.01 km.
//a is the radius of the sphere.
return a * Math.acos((Math.cos(x1)*Math.cos(x2)*Math.cos(y1 - y2)) + (Math.sin(x1)*Math.sin(x2)));
//the great circle distance (distance between the two points (x1, y1) and (x2, y2).
//is given in degrees
}
}