While writing the application, I was faced with the need to perform the entered arithmetic operations. The Lexical Analyzer part returns arithmetic expressions in infix notation, while to perform further operations it's better to have postfix (reverse Polish) notation. In general, I need a stack where immediately after the operation symbol there will be arguments to which the operation should be applied, possibly nested.
I wrote the simplest translation implementation that came to mind, but got an error, the origin of which just can't find.
Example of an input that gives an explicit error: 1+2*3-4/(5*6)
My implementation output is: 12+3*4-56*/
The correct one has to be : 123*+456*/-
Here is the main code, it uses infix Stack
with the source data and postfix StringBuilder
for answer:
for (int i = 0; i < element.length(); i++) {
char st = element.charAt(i);
if (!(st == ' ' || st == ',')) {
if (st == '+' || st == '-' || st == '*' || st == '/') {
while (!infix.isEmpty() && infix.peek() != '(' && operatorWeight(infix.peek()) >= operatorWeight(st)) {
postfix.append(infix.pop());
}
infix.push(st);
} else if (st >= '0' && st <= '9') {
postfix.append(st);
} else if (st == '(') {
infix.push(st);
} else if (st == ')') {
while (!infix.isEmpty() && infix.peek() != '(') {
postfix.append(infix.pop());
}
infix.pop();
}
}
}
while (!infix.isEmpty() && infix.peek() != '(') {
postfix.append(infix.peek());
infix.pop();
}
And here is a helper function for easier compare of operators:
public int operatorWeight(char st) {
int weight = -1;
switch (st) {
case '+':
case '-':
weight = 0;
case '*':
case '/':
weight = 1;
}
return weight;
}
Probably messed up with conditions
You are missing a break statement in the operator comparison switch block.
public int operatorWeight(char st) {
int weight = -1;
switch (st) {
case '+':
case '-':
weight = 0;
break;
case '*':
case '/':
weight = 1;
break;
}
return weight;
}