Java Reference
In-Depth Information
This method isn't complete because you have to consider the case in which the
target zip code doesn't appear in the file. In that case, you exit the loop without hav-
ing returned a value. There are many things the program could do at this point, such
as printing an error message or throwing an exception. To keep things simple, let's
instead return a set of fake coordinates. If the program returns a latitude and longi-
tude of (0, 0), there won't be any matches unless the user asks for an outrageously
high proximity (over 4,000 miles):
public static String find(String target, Scanner input) {
while (input.hasNextLine()) {
String zip = input.nextLine();
String city = input.nextLine();
String coordinates = input.nextLine();
if (zip.equals(target)) {
System.out.println(zip + ": " + city);
return coordinates;
}
}
// at this point we know the zip code isn't in the file
// we return fictitious (no match) coordinates
return "0 0";
}
This method completes the first of the two file-processing tasks. In the second
task, you have to read the file and search for zip codes within the given proximity.
The Scanner doesn't have a reset option for going back to the beginning of the file.
Instead, you have to construct a second Scanner object that will be used for the sec-
ond pass. Thus, your code in main will look like the following:
input = new Scanner(new File("zipcode.txt"));
showMatches(targetCoordinates, input, miles);
The code for finding matches involves a similar file-processing loop that reads
three lines of input at a time, printing matches as it finds them:
public static void showMatches(String targetCoordinates,
Scanner input, double miles) {
// compute lat1 and long1
System.out.println("zip codes within " + miles + " miles:");
while (input.hasNextLine()) {
String zip = input.nextLine();
String city = input.nextLine();
String coordinates = input.nextLine();
// compute lat2 and long2
double distance = distance(lat1, long1, lat2, long2);
Search WWH ::




Custom Search