5

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.

  • why can't you do `if(currChar.equals("*"))`? – No Idea For Name Nov 17 '14 at 09:12
  • There's no "operator" type. Invoke the correct operation based on the string value. – Robby Cornelissen Nov 17 '14 at 09:12
  • Ok. If i get (a+b)*c as input what can i do. –  Nov 17 '14 at 09:15
  • @SURESHKUMARS please post your code! we can't do all the work for you – No Idea For Name Nov 17 '14 at 09:21
  • You still have not specified what is your logic to calculate the value of the expression. Just that you are using the Stack class is not enough information. – Chan Nov 17 '14 at 09:21
  • @SURESHKUMARS, to handle brackets '(' and ')' you could split the string up into multiple sections, handling the inner sections first, possibly a recursive function that returns the result. – Eric Nov 17 '14 at 09:22
  • Could you also be more specific about what 'simple' expressions mean? Could you give a few examples? Do your simple expressions have parenthesis yet? If yes, could you supply a few examples of how you would evaluate those expressions. – Chan Nov 17 '14 at 09:30
  • "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." --> Thanks. Could you also post the code that is doing this incorrectly so we can suggest the corrections. – Chan Nov 17 '14 at 09:31
  • Look into shunting yard algorithm. It copes with operator precedence and brackets. – weston Nov 17 '14 at 10:21

5 Answers5

7

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
No Idea For Name
  • 11,127
  • 10
  • 38
  • 63
  • 3
    Just wondering, is it possible for * to have a lower case form and a upper case form? – committedandroider Nov 17 '14 at 09:16
  • @committedandroider hmm.. probably not, i wanted to ignore whitespaces and thought it does so in ignoreCase. changed it now... – No Idea For Name Nov 17 '14 at 09:19
  • @No Idea For Name I still can't figure what is the current logic the user is using to calculate the value of the expression, what does 'simple' mean when he/she says simple expressions. I mean the original question is yet so undefined and hence I kind of don't understand all these proposed solutions. Just saying.. – Chan Nov 17 '14 at 09:27
  • @Chan i agree with you and for that asked the OP for the code. i want to understand what has he done and what does he expect to receive. – No Idea For Name Nov 17 '14 at 09:30
3

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:
}
committedandroider
  • 7,958
  • 14
  • 59
  • 121
2

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

if (s.equals("+")) {
    // addition
}
Ogen
  • 6,396
  • 5
  • 46
  • 119
2

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();
    }
Jigar Modi
  • 21
  • 2
0

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.

Chan
  • 651
  • 2
  • 8
  • 14