用哈希映射中的值替换字符串值 [英] Replace String values with value in Hash Map

查看:30
本文介绍了用哈希映射中的值替换字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 编程的新手.我创建了一个哈希映射,其中包含我的键值对,用于将用户输入替换为对应于相应键的值.

I'm new to Java Programming. I have created a hash map that contains my Key Value pairs to utilize in replacing user input with the value corresponding to the respective key.

        HashMap<String,String> questionKey = new HashMap<>();             

         for (item : itemSet()) {
             questionKey.put(String.valueOf(item.getOrder()+1), item.getKey());                                
         }                    
        String list = commandObject.getObjectItem().getList();

        if (list.contains("q")){                
            list.replaceAll("q01", questionKey.get("1"));               
            commandObject.getObjectItem().setList(list);
        }             

我在公式评估中使用它

注意:给用户一定的公式特定的输入方式(value1 + value2 + value3)

Note: Users are given a certain formula specific way of entry (value1 + value2 + value3)

我把那个 (value1 value2 value3) 转换成 (value1key value2key value3key)

I'm taking that (value1 value2 value3) and converting it to (value1key value2key value3key)

更新:

我现在更好理解的问题是为了帮助更好地理解如何利用哈希图来评估用户输入.更明确的问题是

The Question as I understand it better now was meant to be to help better understand how to utilize a hashmap in order to evaluate user input. The more clear question would be

评估表达式的最佳方法是什么,即

What would be the best approach to evaluate an expression i.e.

用户输入 = "var1 + var2"

User Input = "var1 + var2"

预期值:valueOf(var1) + valueOf(var2)

Expected Value: valueOf(var1) + valueOf(var2)

?

推荐答案

import java.util.HashMap;

class Program
{
    public static void main(String[] args)
    {
        String pattern = "Q01 + Q02";
        String result = "";

        HashMap<String, String> vals = new HashMap<>();

        vals.put("Q01", "123");
        vals.put("Q02", "123");

        for(HashMap.Entry<String, String> val : vals.entrySet())
        {
            result = pattern.replace(val.getKey(), val.getValue());
            pattern = result;
        }

        System.out.println(result);

    }
}

这篇关于用哈希映射中的值替换字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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