如何从txt文件读取特定值并将其放入HashMap中? [英] How do I read specific values from a txt file and put them into a HashMap?

查看:94
本文介绍了如何从txt文件读取特定值并将其放入HashMap中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的文本文件:

a,9,1

10,5

c,3,4

等...

我试图创建两个hashmaps,其中两个键都是字母,第一个映射的值是第一个数字,第二个映射的值是第二个数字。例如,Map1 = [a,9,b,10,c,3]和Map2 = [a,1,b,5,c,4]

I无法弄清楚如何访问特定的字符和匹配的整数。这是我到目前为止:

pre $ public static void constructLetterMaps()throws FileNotFoundException {
File file2 = new File (fileLoc2);
扫描仪扫描=新扫描仪(文件2);

Map1 = new HashMap< Character,Integer>();
Map2 = new HashMap< Character,Integer>(); (scan.hasNextLine())
{
Map1.put(scan.next(),scan.nextInt());

while
}

}

  while(scan.hasNextLine() )
{
String key =(String)scan.next();
Map1.put(key,scan.nextInt());
Map2.put(key,scan.nextInt());
}

要访问单个密钥,请使用hashmap.get(key) p>

要作为一个整体访问键或条目集,请查看hashmap.entrySet()和keySet()方法。

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());
    }

}

解决方案

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

这篇关于如何从txt文件读取特定值并将其放入HashMap中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆