I am creating a program in which I read the 50 states and their capitals from a .txt file. I then run a while loop and store each of the states in an ArrayList and each of the capitals in another ArrayList. I convert those two ArrayList's to regular arrays, and then run a for loop to store each state as a key in a map, and each capital as a value in the map. My issue is that when I use the map.get() method to return the capital of a particular state it simply returns "null" and I am not sure why that would be the case. Here is my code:
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
public class ChapterOneBasics {
public static void main(String[] args) throws FileNotFoundException {
Map<String, String> usCapitals = new HashMap<String, String>();
ArrayList<String> aList = new ArrayList<>();
ArrayList<String> bList = new ArrayList<>();
int x = 0;
File file = new File("C:\\Private\\Private\\Private\\capitals.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
if(x % 2 == 0) {
aList.add(sc.nextLine());
}
else
bList.add(sc.nextLine());
x++;
}
String[] usStates = aList.toArray(new String[aList.size()]);
String[] uSCapitals = bList.toArray(new String[bList.size()]);
for(int y = 0; y < uSCapitals.length; y++) {
usCapitals.put(usStates[y], uSCapitals[y]);
}
System.out.println(usCapitals.get("Montana"));
}
}
As you can see, I have stored each state to the Map in string format, but whenever I call a state to look up a capital city I get this as the output:
null
I am not sure what the issue is.
put