Alright, so I'm trying to make an expression-as-a-string solver, so that the user can input a string, such as 2+4*5/10, and it will print out the answer, 4. I have some code written, but it doesn't apply the order of operations; it simply solves the equation in order of the operators - e.g. 2+4*5/10 would produce 3, which is incorrect. How do I make it so that multiplication and division are performed first, then addition and subtraction? Here's the code I have right now:
class Expressions
{
String E;
void SetE(String e)
{
E = e;
}
int EvalE()
{
int res = 0;
int temp = 0;
char op = '+';
for(int i=0;i<E.length();i++)
{
if(E.charAt(i)=='*'||E.charAt(i)=='/'||E.charAt(i)=='+'||E.charAt(i)=='-')
{
if(op=='*')res*=temp;
else if(op=='/')res/=temp;
else if(op=='+')res+=temp;
else res-=temp;
temp=0;
op=E.charAt(i);
}
else
{
temp = temp*10+E.charAt(i)-'0';
}
}
if(op=='*')res*=temp;
else if(op=='/')res/=temp;
else if(op=='+')res+=temp;
else res-=temp;
return res;
}
}