2

Creating a double array (one row for states, and one for capitols), I am trying to use 'map.put' in a for loop to save the arrays 'key(states)' and 'value(capitols)' to the HashMap. When using a key from user input after assigning a new HashMap (hMap = getInfo();, My output returns "null". Im not quite sure what it is im doing wrong, but I have a feeling I made an error in the for loop.

public class HashMapProgram {

    public static void main (String[]args) {

        Scanner input = new Scanner(System.in);

        //Assign contents of map in getInfo to hMap
        HashMap<String, String> hMap = getInfo();


        //Prompting user to input a state (key)
            System.out.print("Enter a state, or \"done\" when finished: ");
            String state = input.next();



        if(hMap.get(state) != "done")
                System.out.println("The capital is "+ hMap.get(state));


    }


    public static HashMap<String, String> getInfo(){

        //HashMap to save contents in
        HashMap<String, String> map = new HashMap<>();

        String x[][] = {
                {"Alabama","Alaska","Arizona"  ,"Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia",
                "Hawaii"  ,"Idaho" ,"Illinois" ,"Indiana" ,"Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland",
                "Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey",
                "New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania",  "Rhode Island", "South Carolina",
                "South Dakota", "Tennessee",    "Texas",    "Utah", "Vermont",  "Virginia", "Washington","West Virginia","Wisconsin","Wyoming"},

                {"Montgomery","Juneau","Phoenix","Little Rock","Sacramento","Denver","Hartford","Dover","Tallahassee","Atlanta",
                "Honolulu","Boise","Springfield","Indianapolis","Des Moines","Topeka","Frankfort","Baton Rouge","Augusta", "Annapolis",
                "Boston","Lansing","St. Paul","Jackson","Jefferson City","Helena","Lincoln","Carson City","Concord","Trenton",
                "Santa Fe","Albany","Raleigh","Bismarck","Columbus","Oklahoma City","Salem","Harrisburg","Providence","Columbia",
                "Pierre","Nashville","Austin","Salt Lake City","Montpelier","Richmond","Olympia","Charleston","Madison","Cheyenne"}

        };



        //Saving contents in 'map'
        for(int i = 0; i < x.length; i++) {     
            map.put(x[0][i], x[1][i]);  
        }

        return map;
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
J.Soto
  • 45
  • 3
  • change `i < x.length` to `i < x[0].length` – Kartik Mar 07 '19 at 04:39
  • Thank you so much, but I have a dumb question. What is the difference between x.length and x[0].length? Is it because it grabs one individual row of 50 than the length of the whole array? – J.Soto Mar 07 '19 at 04:45
  • That's right. See my answer for more details. – Kartik Mar 07 '19 at 04:46
  • @J.Soto Java does not have true multidimensional arrays, it has an array of arrays. So your code `x.length` is asking for the number of arrays in the array. You have 2 arrays, the states and the cities. See [this Answer](https://stackoverflow.com/a/7913679/642706) on another Question. – Basil Bourque Mar 07 '19 at 04:57

1 Answers1

3

There are a few errors:

1) In your for-loop, change i < x.length; to i < x[0].length;, otherwise you're running the loop just 2 times.

2) Don't compare strings using !=. Use equals() instead. See this for more details.

3) You don't have a loop to ask for user input repeatedly. Change your code in main() to:

Scanner input = new Scanner(System.in);
HashMap<String, String> hMap = getInfo();
String state = "";
do {
    System.out.print("Enter a state, or \"done\" when finished: ");
    state = input.next();
    System.out.println("The capital is " + hMap.get(state));
} while (!state.equals("done")); 

4) Work with interface, not class. So change

HashMap<String, String> hMap = getInfo();

to

Map<String, String> hMap = getInfo();

and also update the method signature to return Map<String, String>.

5) Since Java 9, you can directly create a map like this:

Map<String, String> m = Map.of(
        "Alabama", "Montgomery",
        "Alaska", "Juneau",
        "Arizona", "Phoenix"
        //and so on...
);
Kartik
  • 7,677
  • 4
  • 28
  • 50
  • See the corrected `for` loop code run live at IdeOne.com: https://ideone.com/AlDcd4 – Basil Bourque Mar 07 '19 at 04:50
  • You are awesome, thanks for the in depth explanation!! – J.Soto Mar 07 '19 at 04:54
  • Thank you for the extended information, but I had to specifically "create a two dimensional array of Strings initialized to store the 50 states in the first column and their corresponding capital in the second column" as instructed – J.Soto Mar 07 '19 at 05:09
  • @J.Soto No worries. This community helps you with best practices in real world, not constrained by homework requirements. – Kartik Mar 07 '19 at 05:12