In: Computer Science
Write a java program that will read a file called stateinfo.txt and will store the information of the file into a map. The stateinfo.txt file contains the names of some states and their capitals. The format of stateinfo.txt file is as follows.
State Capital
--------- -----------
NSW Sydney
VIC Melbourne
WA Perth
TAS Tasmania
QLD Brisbane
SA Adelaide
The program then prompts the user to enter the name of a state. Upon receiving the user input, the program should display the name of the capital for that particular state. Assume that the name of the state that a user may enter already exists in the stateinfo.txt file.
SourceCode:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class SearchCapitals { public static void main(String args[]){ //Declaring the variables String stateName; //Creating the scanner object for getting input from user Scanner scanner = new Scanner(System.in); //Creating the Map objects Map<String,String> map=new HashMap<String,String>(); //Creating the BufferedReader objects for reading the text file BufferedReader reader; //Reading the the text file try { reader = new BufferedReader(new FileReader("stateinfo.txt")); String line = reader.readLine(); //Reading the file line by line until the end of the file is reached while (line != null) { //Spliting the line in words String data[] = line.split(" "); map.put(data[0],data[1]); //Puting the data to the map //read next line line = reader.readLine(); } reader.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Please enter name of the state: "); stateName = scanner.nextLine(); System.out.println("Capital of " + stateName + " is " + map.get(stateName)); } }
OUTPUT: