Convert String to operator(+*/-) in java

前端 未结 5 1252
时光说笑
时光说笑 2021-01-06 05:57

I am using Stack class to calculate simple arithmetic expressions involving integers, such as 1+2*3.your program would execute operations in the order given,without regardin

相关标签:
5条回答
  • 2021-01-06 06:37

    Do what Ogen suggested and manually check the operator. A quick shortcut to doing the if, else if .... structure is switch, that is

    switch(operand) {
    case "*":
          break;
    case "+":
          break; 
     .....
     default:
    }
    
    0 讨论(0)
  • 2021-01-06 06:46

    Quick solution: Use below code for executing correct javascript Arithmetic expression in java.

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine se = manager.getEngineByName("JavaScript");        
        try {
            Object result = se.eval(val);
            System.out.println(result.toString());
        } catch (ScriptException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    0 讨论(0)
  • 2021-01-06 06:51

    probably the best way to do it will be equals, but it's best to ignore whitespaces:

    i'm not quite sure how you split your string, but for example, if you have a char op and two integer a and b:

    String str = op.replace(" ", "");
    
    if(str.equals("*")){
       retVal = a*b;
    } else if(str.equals("+")){
       retVal = a+b;
    }//etc
    
    0 讨论(0)
  • 2021-01-06 06:51

    Ok, assuming your assignment needs you to use the Stack class and you already have the logic to pick numbers ( including the negative numbers -- that would an operator followed by another operator in all but one cases) and operators and parens, what you could do is as follows.

    If you encounter a number, pop the last two elements from your stack. The first item you pop will be an operator and the next will be a number. Evaluate the expression and push it into Stack and continue.

    You can ignore the parenthesis. You will also have to handle the case of reading a number or parenthesis the first time.

    0 讨论(0)
  • 2021-01-06 07:03

    You will have to manually check and assign the operator. E.g.

    if (s.equals("+")) {
        // addition
    }
    
    0 讨论(0)
提交回复
热议问题