Java Reference
In-Depth Information
We won't dwell on the math involved here, but a short explanation might be help-
ful. Imagine forming a triangle by connecting two points with the North Pole. From
the two latitudes, you can compute the distance from each point to the North Pole.
The difference between the two longitudes tells you the angle formed by these two
sides of the triangle. You may recall from geometry class that if you know two sides
and the angle between them, then you can compute the third side. We are using a spe-
cial version of the law of cosines that works for spheres to compute the length of the
third side of the triangle (which is the line connecting the two points on our sphere).
We have to convert from degrees into radians and we have to include the radius of
our sphere (in this case the Earth). The resulting calculation is included in the final
version of the program.
Here is the complete version of the program:
1 // This program uses a file of zip code information to allow a user
2 // to find zip codes within a certain distance of another zip code.
3
4 import java.util.*;
5 import java.io.*;
6
7 public class ZipLookup {
8
// radius of sphere. Here it's the Earth, in miles
9
public static final double RADIUS = 3956.6;
10
11
public static void main(String[] args)
12
throws FileNotFoundException {
13
giveIntro();
14
Scanner console = new Scanner(System.in);
15
16
System.out.print("What zip code are you interested in? ");
17
String target = console.next();
18
System.out.print("And what proximity (in miles)? ");
19
double miles = console.nextDouble();
20
System.out.println();
21
22
Scanner input = new Scanner( new File("zipcode.txt"));
23
String targetCoordinates = find(target, input);
24
input = new Scanner( new File("zipcode.txt"));
25
showMatches(targetCoordinates, input, miles);
26
}
27
28
// introduces the program to the user
29
public static void giveIntro() {
30
System.out.println("Welcome to the zip code database.");
31
System.out.println("Give me a 5-digit zip code and a");
Search WWH ::




Custom Search