Write a complete Java program to use Map to construct a dictionary for airport c
ID: 3721188 • Letter: W
Question
Write a complete Java program to use Map to construct a dictionary for airport code and airport city. The program should read from a text file (input.txt") to construct the dictionary and also all ow user to search for airport code based on airport city. Each line in the text file is a pair of airport code and city separated by a TAB key. Once the file is read and the dictionary is constructed, the program should ask user to enter an airport city and then search and display the code of corresponding airport(s) if found. The program will then decide whether to continue or not by asking user. For example, the user may type Chicago and it should return ORD The sample input file looks like this:
RDU Raleigh/Durham
SFO San Francisco
ORD Chicago
Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class dictionary {
private static Map <String,String> codesAndDescs = new HashMap<String,String>();
private static Boolean found ;
public static void main(String args[]) {
Scanner scan;
try {
scan = new Scanner(new File("input.txt"));
while(scan.hasNext()){
String curLine = scan.nextLine();
String[] splitOnTab = curLine.split(" ");
codesAndDescs.put(splitOnTab[0],splitOnTab[1]);
}
scan.close();
System.out.println("Enter the Airport City name to search for its code ");
Scanner scanner = new Scanner(System.in);
String airportCityName = scanner.nextLine();
for (Map.Entry<String, String> codesAndDesc : codesAndDescs.entrySet()) {
if((codesAndDesc.getValue().trim()).equals(airportCityName.trim())) {
System.out.println(codesAndDesc.getKey());
found = true;
}
if(found!=true)
System.out.println("Code not found for the given city");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.