1
+ package ch_21 ;
2
+
3
+ import java .util .HashMap ;
4
+ import java .util .Map ;
5
+ import java .util .Scanner ;
6
+
7
+ /**
8
+ * *21.9 (Guess the capitals using maps) Rewrite Programming Exercise 8.37 to store
9
+ * pairs of each state and its capital in a map. Your program should prompt the user
10
+ * to enter a state and should display the capital for the state.
11
+ * <p>
12
+ * {@linkplain ch_08.Exercise08_37}
13
+ */
14
+ public class Exercise21_09 {
15
+ public static void main (String [] args ) {
16
+ String [][] statesAndCaptials = {
17
+ {"Alabama" , "Montgomery" }, {"Alaska" , "Juneau" }, {"Arizona" , "Phoenix" },
18
+ {"Arkansas" , "Little Rock" }, {"California" , "Sacramento" },
19
+ {"Colorado" , "Denver" }, {"Connecticut" , "Hartford" },
20
+ {"Delaware" , "Dover" }, {"Florida" , "Tallahassee" },
21
+ {"Georgia" , "Atlanta" }, {"Hawaii" , "Honolulu" }, {"Idaho" , "Boise" },
22
+ {"Illinois" , "Springfield" }, {"Indiana" , "Indianapolis" },
23
+ {"Iowa Des" , "Moines" }, {"Kansas" , "Topeka" }, {"Kentucky" , "Frankfort" },
24
+ {"Louisiana" , "Baton Rouge" }, {"Maine" , "Augusta" },
25
+ {"Maryland" , "Annapolis" }, {"Massachusetts" , "Boston" },
26
+ {"Michigan" , "Lansing" }, {"Minnesota" , "Saint Paul" },
27
+ {"Mississippi" , "Jackson" }, {"Missouri" , "Jefferson City" },
28
+ {"Montana" , "Helena" }, {"Nebraska" , "Lincoln" },
29
+ {"Nevada" , "Carson City" }, {"New Hampshire" , "Concord" },
30
+ {"New Jersey" , "Trenton" }, {"New Mexico" , "Santa Fe" },
31
+ {"New York" , "Albany" }, {"North Carolina" , "Raleigh" },
32
+ {"North Dakota" , "Bismarck" }, {"Ohio" , "Columbus" },
33
+ {"Oklahoma" , "Oklahoma City" }, {"Oregon" , "Salem" },
34
+ {"Pennsylvania" , "Harrisburg" }, {"Rhode Island" , "Providence" },
35
+ {"South Carolina" , "Columbia" }, {"South Dakota" , "Pierre" },
36
+ {"Tennessee" , "Nashville" }, {"Texas" , "Austin" },
37
+ {"Utah" , "Salt Lake City" }, {"Vermont" , "Montpelier" },
38
+ {"Virginia" , "Richmond" }, {"Washington" , "Olympia" },
39
+ {"West Virginia" , "Charleston" }, {"Wisconsin" , "Madison" },
40
+ {"Wyoming" , "Cheyenne" }
41
+ };
42
+
43
+ Map <String , String > stateCapitalsMap = new HashMap <>();
44
+ for (String [] pair : statesAndCaptials ) {
45
+ stateCapitalsMap .putIfAbsent (pair [0 ], pair [1 ]);
46
+ }
47
+
48
+ Scanner in = new Scanner (System .in );
49
+ System .out .print ("Enter a state: " );
50
+ String userInput = in .nextLine ().trim ();
51
+
52
+ if (stateCapitalsMap .containsKey (userInput )) {
53
+ System .out .println ("The capital of " + userInput + " is " + stateCapitalsMap .get (userInput ));
54
+ } else {
55
+ System .out .println ("We could not find a capital for the state: " + userInput );
56
+ }
57
+
58
+ in .close ();
59
+ }
60
+
61
+ }
0 commit comments