Answer: See the Java program below (one file containing the main program and a GeoLocation class). It reads the four numbers, computes the great‑circle distance (in miles) and prints the result in the same format as the sample.
Explanation: This uses the spherical law of cosines to compute the central angle between two latitude/longitude points (converted to radians) and multiplies by the Earth radius in miles.
Code:
import java.util.Scanner;
public class Exercise4_3_8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the latitude of the starting location: ");
double lat1 = input.nextDouble();
System.out.print("Enter the longitude of the starting location: ");
double lon1 = input.nextDouble();
System.out.print("Enter the latitude of the ending location: ");
double lat2 = input.nextDouble();
System.out.print("Enter the longitude of the ending location: ");
double lon2 = input.nextDouble();
GeoLocation start = new GeoLocation(lat1, lon1);
GeoLocation end = new GeoLocation(lat2, lon2);
double distance = start.distanceTo(end);
System.out.println("The distance is " + distance + " miles.");
}
}
class GeoLocation {
private double latitude;
private double longitude;
public GeoLocation(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
/**
* Returns the distance between this location and another location in miles.
* Uses the spherical law of cosines.
*/
public double distanceTo(GeoLocation other) {
double lat1 = Math.toRadians(this.latitude);
double lon1 = Math.toRadians(this.longitude);
double lat2 = Math.toRadians(other.latitude);
double lon2 = Math.toRadians(other.longitude);
double centralAngle = Math.acos(
Math.sin(lat1) * Math.sin(lat2) +
Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)
);
double earthRadiusMiles = 3958.7613; // average Earth radius in miles
return earthRadiusMiles * centralAngle;
}
}
Steps:
- Read four doubles from the user (start latitude, start longitude, end latitude, end longitude).
- Convert latitudes/longitudes to radians.
- Compute the central angle using the spherical law of cosines.
- Multiply the central angle by Earth’s radius in miles to get the distance.
- Print the distance as shown.
If you prefer the haversine formula (more numerically stable for very small distances), I can provide that variant.