Java Reference
In-Depth Information
First consider the problem of finding the coordinates for the target zip code. You
need to set up a Scanner to read from the file, and then you need to call the method
that will do the search. But what information should the searching method return?
You want the coordinates of the target zip code (the latitude and longitude). Your
method can't return two different values, but these coordinates appear on a single line
of input, so you can return that line of input as a String . That means that your main
method will include the following code:
Scanner input = new Scanner(new File("zipcode.txt"));
String targetCoordinates = find(target, input);
The method should read the input file line by line, searching for the target zip
code. Remember that each entry in the file is composed of three different lines. As a
result, you need a slight variation of the standard line-processing loop that reads three
lines each time through the loop:
public static String find(String target, Scanner input) {
while (input.hasNextLine()) {
String zip = input.nextLine();
String city = input.nextLine();
String coordinates = input.nextLine();
...
}
...
}
As you read various zip code entries, you want to test each to see whether
it matches the target. Remember that you need to use the equals method to
compare strings for equality. If you find a match, you can print it and return the
coordinates:
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;
}
}
...
}
Search WWH ::




Custom Search