问题
I have a text file that looks like this:
a, 9, 1
b, 10, 5
c, 3, 4
etc...
I am trying to create two hashmaps where the keys in both are the letters, the values for the first map are the first number, and values for the second map are the second number. For example, Map1 = [a, 9, b, 10, c, 3] and Map2 = [a, 1, b, 5, c, 4]
I can't figure out how to access the specific character and matching integer. Here is what I have so far:
public static void constructLetterMaps() throws FileNotFoundException{
File file2 = new File(fileLoc2);
Scanner scan = new Scanner(file2);
Map1 = new HashMap<Character, Integer>();
Map2 = new HashMap<Character, Integer>();
while(scan.hasNextLine())
{
Map1.put(scan.next(), scan.nextInt());
}
}
回答1:
You could try this to populate the maps:
while(scan.hasNextLine())
{
String key = (String) scan.next();
Map1.put(key, scan.nextInt());
Map2.put(key, scan.nextInt());
}
To access a single key, use hashmap.get(key).
To access the key or entry set as a whole, check out hashmap.entrySet() and keySet() methods
来源:https://stackoverflow.com/questions/29837331/how-do-i-read-specific-values-from-a-txt-file-and-put-them-into-a-hashmap