Java Reference
In-Depth Information
if (distance <= miles) {
// print zip code
}
}
}
Again, this is an incomplete version of the method. It indicates that before the loop
begins you will compute two values known as lat1 and long1 that represent the lati-
tude and longitude of the target coordinates. Inside the loop you compute values for
lat2 and long2 that represent the latitude and longitude of the next entry from the
data file. The latitude and longitude are stored in a String . You can construct a
Scanner for each String that can be used to pull out the individual tokens. You also
need to fill in the details of printing. This is a good place to use a printf to format
the output:
public static void showMatches(String targetCoordinates,
Scanner input, double miles) {
Scanner data = new Scanner(targetCoordinates);
double lat1 = data.nextDouble();
double long1 = data.nextDouble();
System.out.println("zip codes within " + miles + " miles:");
while (input.hasNextLine()) {
String zip = input.nextLine();
String city = input.nextLine();
String coordinates = input.nextLine();
data = new Scanner(coordinates);
double lat2 = data.nextDouble();
double long2 = data.nextDouble();
double distance = distance(lat1, long1, lat2, long2);
if (distance <= miles) {
System.out.printf(" %s %s, %3.2f miles\n",
zip, city, distance);
}
}
}
This addition almost completes the program. The preceding code calls a method
called distance that is intended to compute the distance between two points, given
their latitude and longitude. This problem was included as Programming Project 5 in
Chapter 3. You can use the following standard formula:
Let
1 ,
1 , and
2 ,
2 be the latitude and longitude of two points, respectively.
Δ
,
the longitudinal difference, and
, the angular difference/distance in radians, can be
determined from the spherical law of cosines as:
Δσ
= arccos(sin
1 sin
2 + cos
1 cos
2 cos
)
Search WWH ::




Custom Search