java - 如何替换字符串中的“x”并等同于数字?
问题描述
给定一个只有数字、数学运算符和“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) 后正确。
解决方案
- 替换
x
数字后 - 替换独立
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
推荐阅读
- ios - 如何在swift中解析分组嵌套字典
- oracle - 变量和proc oracle的问题
- csv - 如何将 annotations.tsv 文件加载到 Google 自定义搜索引擎?
- python - 使用 Beautiful Soup 查找具有部分 id 值的标签
- python - Pygame矩形位置不更新
- angular - 导入时超出最大预算警告 ~@angular/material/theming
- json - Swift 中 JSON 的变量结构
- vba - 将所有单词转换为标题大小写,首字母缩略词除外
- javascript - 公式更新单元格时运行 Google 表格脚本
- javascript - 如何在使用 knex.js 删除约束之前检查约束是否存在