7-46 表达式计算分数 10
Write a program that reads an expression in a line as input and prints out the result. Only non-negative integers and operators below are allowed in the expression:
+ - * / % ( )
输入格式:
A line of expression.
输出格式:
The result.
输入样例:
(2+32)/2-6
输出样例:
11
以下是答案
import java.util.Scanner;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
//这个方法太高级了
public class Pta_7_46 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
// 使用 eval 方法计算表达式
Object result = engine.eval(a);
System.out.println(result);
} catch (ScriptException e) {
e.printStackTrace();
}
}
}