有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java当值位于ArrayList中时,如何继续向已经存在的键添加值?输入来自扫描仪以创建树状图

我试图接收来自用户的输入,其中每一行必须包含一些文本(一个键),后跟一个制表符,后跟一个double文本(一个值),后跟一个换行符

如果允许用户继续输入同一个键,然后输入/t,然后输入不同的值和/n,那么我如何编写一个程序,将值不断添加到树映射中的同一个键

每个键都有一个ArrayList,这就是我被卡住的地方,因为我不知道如何为不同的行/键不断添加到数组列表中

这就是我目前的情况:

    TreeMap<String, ArrayList<Double>> categoryMap = new TreeMap<>();

    Double val = 0.0;
    String inputKey = "";

    System.out.println("Welcome, please enter text");
    Scanner scn = new Scanner(System.in);
    dataSource = scn;

    try
    {
        // adds all words of input to a string array
        while (dataSource.hasNextLine())
        {
            ArrayList<Double> valueMap = new ArrayList<>();
            inputKey = dataSource.next();

            val = dataSource.nextDouble();
            valueMap.add(val);

            if (categoryMap.get(inputKey) == null)
            {
                categoryMap.put(inputKey, valueMap);
            }
            else
            {
                categoryMap.put(inputKey, valueMap);
            }

            dataSource.nextLine();
        }
    }
    // Exception if no lines detected and shows message
    catch (IllegalArgumentException lineExcpt)
    {
        System.out.println("No lines have been input: " + lineExcpt.getMessage());
    }
    finally
    {
        scn.close();
    }

    return categoryMap;

我对java非常陌生,只有大约一个月的经验


共 (2) 个答案

  1. # 1 楼答案

    这是while循环中的逻辑,需要进行一些修改。当前,每次都会用一个新的值列表覆盖该值列表

    以下是你在纸上看到的:

    • 如果键不存在,则使用给定的double创建一个新列表,并将其用作值
    • 否则,获取(已经存在的)列表并将double添加到其中

    在代码中,我们只需要修改您所做的:

    String inputKey = dataSource.next();
    double val = dataSource.nextDouble();
    List<Double> list = categoryMap.get(inputKey);
    
    if (list == null)                    // If the key does not exist
    {
        list  = new ArrayList<>();       // create a new list
        list.add(val);                   // with the given double
        categoryMap.put(inputKey, list); // and use it as the value
    }
    else                                 // Else
    {
        list.add(val)                    // (got the list already) add the double to it
    }
    
  2. # 2 楼答案

    如果您使用Java 8,则映射有computeIfAbsent方法

    List<Double> addTo = map.computeIfAbsent(key, ArrayList::new);