Java 计算算式字符串

调用JS

static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript"); 

public static void main(String[] args) {
String strs = "(x+1)*1.5";  
String a = strs.replaceAll("x", "6");
        try {  
        System.out.println(a);
            System.out.println(jse.eval(a));  
        } catch (Exception t) {  
        }  
}
以下是一个简单的Java程序,可以从文件中读取数学算式计算出结果: ```java import java.io.BufferedReader; import java.io.FileReader; public class MathExpressionEvaluator { public static void main(String[] args) { String fileName = "mathexpression.txt"; // replace with the name of your file try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); String line = reader.readLine(); while (line != null) { double result = evaluate(line); System.out.println(line + " = " + result); line = reader.readLine(); } reader.close(); } catch (Exception e) { System.out.println("Error reading file: " + e.getMessage()); } } public static double evaluate(String expression) { String[] tokens = expression.split(" "); double result = Double.parseDouble(tokens[0]); for (int i = 1; i < tokens.length; i += 2) { String operator = tokens[i]; double operand = Double.parseDouble(tokens[i + 1]); if (operator.equals("+")) { result += operand; } else if (operator.equals("-")) { result -= operand; } else if (operator.equals("*")) { result *= operand; } else if (operator.equals("/")) { result /= operand; } } return result; } } ``` 该程序首先从文件中读取数学算式,然后逐行计算并输出结果。 evaluate() 方法将每个算式转换为一个字符串数组,其中每个元素都是一个数字或运算符。然后它使用类似于栈的方式计算表达式的值,并返回结果。 注意:该程序假设算式中只包含加减乘除四种运算符,且每个数字和运算符之间都用空格分隔。如果你的算式包含其他运算符或没有使用空格分隔数字和运算符,则需要修改 evaluate() 方法以适应这些情况。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值