Search code examples
javaoperators

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


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 regarding to the precedence of operators. *Thus, the expression 1+2*3 should be calculated (1+2)*3=9,not 1+(2*3)=7.

If i get the input as 1+2*3,i know how to convert the string 1,2,3 to Integer.but i don't know how to covert +,* from string type to operator.

My code logic is: For eg: Given string 2 + (3 * 5), So 3 * 5 will be operated first then +2 will be performed in result of 3 * 5.


Solution

  • 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