【问题标题】:replacing unknown variables in equation替换方程中的未知变量
【发布时间】:2015-02-16 07:57:42
【问题描述】:

所以我们有:

    String test2 = "12+x+43+y+32-100";
    Map<String, String> values = new HashMap<String, String>();
    values.put("x", "3");
    values.put("y", "7");

    for (String key : values.keySet()) {
        if (test2.contains(key)) {
            String result = test2.replaceAll(key, values.get(key));
            System.out.println(result);
        }
    }

输出:

12+3+43+y+32-100

12+x+43+7+32-100

虽然应该是:

12+3+43+7+32-100

【问题讨论】:

    标签: java string variables math evaluation


    【解决方案1】:

    result 替换为test2

                test2= test2.replaceAll(key,values.get(key));
                System.out.println(test2);
    

    如果你在每次运行时创建一个新变量result,你会得到一个新字符串,其中只有一个变量被替换

    【讨论】:

      【解决方案2】:

      在你的 for 循环中,找到 x 后,它被替换为 3。然后它打印 12+3+43+y+32-100 然后再次循环检查字母。然后它找到 y 并用 7 替换。但以前的变量 x 不会受到影响。因此,将打印 12+x+43+7+32-100。

      【讨论】:

        【解决方案3】:

        Java String 对象是不可变的。 replaceAll() 方法返回一个应用了操作的新 String 对象,并且您的 test2 对象没有改变。

        因此,您必须在结果对象中应用新的修改,或者使用返回的对象重新分配 test2 对象。

        for (String key : values.keySet()) {
            if (test2.contains(key)) {
                test2 = test2.replaceAll(key, values.get(key));
                System.out.println(test2);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-27
          相关资源
          最近更新 更多