【问题标题】:How to replace "x" in string and equate to a number?如何替换字符串中的“x”并等同于数字?
【发布时间】:2021-12-24 07:02:03
【问题描述】:

给定一个只有数字、数学运算符和“x”的字符串,以及一个替换 x 的数字,你将如何替换字符串中的所有 x,然后将字符串等同于一个答案?到目前为止,我是这样的:

String str = "2+4x"; //Example string, could be [2 +4x -  5/ 4 - 9( 6+1*x)] or [4x+0]
Float numToReplace = 20.4; //Has to be Float, cannot use Double


str = str.replace("x", numToReplace);

// How to simplify the string into a number?

我无法将字符串等同起来,我也无法弄清楚如何摆脱“隐含乘法”(当用户输入“2x”时,我想将其更改为 (2*x) 以便替换 x) 后方程可以正常工作。

【问题讨论】:

标签: java equation


【解决方案1】:
  1. 在数字后替换x
  2. 替换独立x
String str = "2+4x * x";
float numToReplace = 20.4f;

String expr = str
    .replaceAll("(\\d+)x", "$1 * " + numToReplace)
    .replaceAll("x", Float.toString(numToReplace);

可以使用 Nashorn 脚本引擎评估生成的表达式,但它已被弃用:

public static void main(String ... args) throws ScriptException {
    String str = "2+4x * x";
    float numToReplace = 20.4f;

    String expr = str
        .replaceAll("(\\d+)x", "$1 * " + numToReplace)
        .replaceAll("x", Float.toString(numToReplace);

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");

    // a checked ScriptException may be thrown
    System.out.println(expr + " = " + engine.eval(expr));

    float result = Float.parseFloat(engine.eval(expr));
    System.out.println("result = " + result);
}

展示著名的浮点功能的输出:

2+4 * 20.4 * 20.4 = 1666.6399999999999
result = 1666.64

【讨论】:

  • 那么我如何将“str”简化为单个数字?
  • @GSDV,请检查更新
  • 我能够导入正确的东西,但现在我的错误消息是“engine.eval(expr)”的“无法将对象转换为浮点数”(我需要将值存储为浮点数) .
  • @GSDV,你应该打电话给Float.parseFloat(engine.eval(expr).toString()),检查更新。
  • 现在它说“未报告的异常 ScriptException;必须被捕获或声明为抛出”,箭头指向“expr”
猜你喜欢
  • 1970-01-01
  • 2019-10-01
  • 2020-04-05
  • 2017-06-27
  • 2015-12-25
  • 2021-11-25
  • 1970-01-01
  • 2013-12-15
  • 2015-09-13
相关资源
最近更新 更多