我用Scanner在控制台随意输入一段数学运算式,比如(3+5)*2
如何计算出结果?
有网友说:“用一个String类型的数组,将输入的字符串保存起来。然后对每一个char进行判断。如果要对所有的操作类型都判断,那么则涉及到对运算符号的配对以及优先级处理。如果只是题目中的一串,只需要用数组保存之后对每个字符进行判断即可。”
但是不知道怎么做,而且运算式是随机输入的,并不一定这么简单,可能有多个括号。
有哪位大神能帮忙解决这个问题,谢谢java

解决方案 »

  1.   

    看看这个行不行,网上找的。
    http://blog.csdn.net/lip009/article/details/7768258
      

  2.   


    import java.util.Stack;
    public class Evaluation { public static void main(String[] args) {
    // Check number of arguments passed
    if (args.length != 1) {
    System.out.println(
    "Usage: java EvaluateExpression \"expression\"");
    System.exit(1);
    } try {
    System.out.println(evaluateExpression(args[0]) );
    }catch (Exception ex) {
    System.out.println("Wrong expression: " + args[0]);
    }
    } /** Evaluate an expression */
    public static int evaluateExpression(String expression) {
    // Create operandStack to store operands
    Stack<Integer> operandStack= new Stack<Integer>();
    // Create operatorStack to store operators
    Stack<Character> operatorStack= new Stack<Character>();

    // Insert blanks around (, ), +, -, /, and *
    expression = insertBlanks(expression); // Extract operands and operators
    String[] tokens = expression.split(" ");

    // Phase 1: Scan tokens
    for(String token : tokens){
    if(token.length() == 0){
    continue; // Back to the while loop to extract the next token
    }else if(token.charAt(0) == '+' || token.charAt(0) == '-'){
    // Process all +, -, *, / in the top of the operator stack
    while (!operatorStack.isEmpty() &&
       (operatorStack.peek() == '+' ||
       operatorStack.peek() == '-' ||
       operatorStack.peek() == '*' ||
       operatorStack.peek() == '/')) {
    processAnOperator(operandStack, operatorStack);
    }
    // Push the + or - operator into the operator stack
    operatorStack.push(token.charAt(0));
    }else if(token.trim().charAt(0) == '('){
    operatorStack.push('('); //push '(' to stack
    }else if(token.trim().charAt(0) == ')'){
    while(operatorStack.peek() != '('){
    processAnOperator(operandStack, operatorStack);
    }
    operatorStack.pop(); //Pop the '(' symbol from the stack
    }else{ // An operand scanned
    //push an operand to the stack
    operandStack.push(new Integer(token));
    }
    }
    // Phase 2: Process all the remaining operators in the stack
    while(!operatorStack.isEmpty()){
    processAnOperator(operandStack, operatorStack);
    }
    // Return the result
    return operandStack.pop();
    } /** Process one operator: Take an operator from operatorStack and
    apply it on the operands in the operandStack */
    public static void processAnOperator(
    Stack<Integer> operandStack, Stack<Character> operatorStack) {
    char op = operatorStack.pop();
    int op1 = operandStack.pop();
    int op2 = operandStack.pop();
    if (op == '+')
    operandStack.push(op2 + op1);
    else if (op == '-')
    operandStack.push(op2 - op1);
    else if (op == '*')
    operandStack.push(op2 * op1);
    else if (op == '/')
    operandStack.push(op2 / op1);
    } public static String insertBlanks(String s) {
    String result = ""; for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == '(' || s.charAt(i) == ')' ||
    s.charAt(i) == '+' || s.charAt(i) == '-' ||
    s.charAt(i) == '*' || s.charAt(i) == '/')
    result += " " + s.charAt(i) + " ";
    else{
    result += s.charAt(i);
    }
    }
    return result;
    }
    }
      

  3.   

    public static void main(String args[]) {
    while (true) {
    BufferedReader br = new BufferedReader(new InputStreamReader(
    System.in));
    System.out.print("请输入一个算式:");
    try {
    String str = br.readLine();
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    Object o = engine.eval(str);
    double d = Double.parseDouble(o.toString());
    System.out.println(str + " = " + d);
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }
    }
      

  4.   

    直接用js的eval函数jdk 1.6后新增的调用脚本语言import javax.script.Bindings;
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    public class Test {
    public static void main(String[] args) throws Exception {
    ScriptEngineManager manager=new ScriptEngineManager();
    ScriptEngine engine=manager.getEngineByExtension("js");
    Bindings bindings=engine.createBindings();
    String expression="(564-454)*10/2";
    bindings.put("expression", expression);
    Double value=(Double) engine.eval("eval(expression)", bindings);
    System.out.println(value);
    }
    }