-1

I need to modify this code in order to use order of operations and to be able to multiply and divide but I have no idea where to start. I know if works for addition and subtraction but I just need to figure out how to make it multiply and divide.

import java.util.Scanner;
class Expressions {
String e;

void setExpressions(String exp){
    e =exp;
}
int evaluate1(){
    //e has +. -. only, single digit numbers
    int r = e.charAt(0)-'0';
    int l = e.length();
    for(int i=1; i<=l-1; i++ )
        if (e.charAt(i) == '+')
            r += (e.charAt(i+1)-48);
        else 
            r -= (e.charAt(i+1)-'0');
    return r;
                }

int evaluateAS(){
    //e has +, -, only, multiple digit numbers
    int r = 0;
    int n = 0;
    int op = '+'; //+, -

    for(int i=0; i<e.length(); i++ ){
        if (e.charAt(i) == '-' || e.charAt(i) == '+'){
                if (op == '+')
                    r += n;
                else
                    r -= n;
                    n = 0;
                    op = e.charAt(i);
                }
                else //digits
                    n = n*10+(e.charAt(i) - '0');
        }
    if (op == '+')
        r += n;
    else
        r -= n;
    return r;
}
}
public class Runner {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    Expressions myE = new Expressions();

    System.out.println("Enter E: ");
    String e = in.next();

    myE.setExpressions(e);
    //int r = myE.evaluate1();
    int r = myE.evaluateAS();
    System.out.println(e+" = "+ r);
}
}
  • What part did you get stuck on when you tried to make it also multiply and divide? – Dennis Meng Nov 05 '13 at 17:57
  • Right now all it can do is add and subtract but I have no idea where to start to make it multiply and divide as well. – user2957438 Nov 05 '13 at 17:59
  • 1
    Since this looks like your first question, I'll give you a tip: "i need to add code to do..." questions are either off-topic or very close to being off-topic. For questions like these, it's best if you make an honest attempt on your own, and then only post here if you can't understand why your attempt doesn't work. – Dennis Meng Nov 05 '13 at 18:02

1 Answers1

0

Multiplication (or division) together with addition requires priority, which means that you cannot continue to evaluate your expression from left to right.

Usually, computation parsers use the reversed polish notation (http://en.wikipedia.org/wiki/Reversed_Polish_notation) which gives you a tree representation of the mathematical expression. The wikipedia article contains many information as too how to use this.

Typically, you'll use the Shunting-yard algorithm to convert your infix (usual) notation to RPN, then you'll see how easy it is to evaluate an expression represented in the RPN.

njzk2
  • 38,969
  • 7
  • 69
  • 107