I'm completing this code for class where we convert from infix to postfix in one method and calculate the postfix in another. I'm running first into the problem where my logic for the conversion part isn't right because even if I run 12-3, the postfix shows as 3 instead of 12 3 -. Secondly, I'm not sure how check precedence while in the method. The calculator framework code was given
The differences between == and .equals() was addressed in this question How do I compare strings in Java? but I tried parsing the delims strings into chars as well and the postfix still gave the same result of 3.
public String infixToPostfix() {
Stack<String> s = new Stack<>();
String expression = jtfInfix.getText(); // retrieves one long string
String delims = "+-*/() ";
StringTokenizer strToken = new StringTokenizer(expression, delims, true); // without true, it'll skip the tokens
// and move onto the next string
String postFix = "";
while (strToken.hasMoreTokens()) {
String token = strToken.nextToken();
// if the next token is a number, append it to the result
if (token != delims) {
postFix += token;
} else if (token == "(") {
s.push(delims);
while (delims != ")") {
postFix += token;
try {
s.pop();
} catch (StackEmptyException see) {
see.printStackTrace();
}
}
}
// else if the next token is an operator
else if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
// compare the token to the top of the stack to determine precedence
// while the operator on the stack has precedence
// pop the top element off the stack and append it to the result
try {
postFix += s.pop();
} catch (StackEmptyException see) {
see.printStackTrace();
}
// push the current operator on the stack
s.push(token);
}
while (!s.isEmpty()) {
try {
postFix += s.pop();
} catch (StackEmptyException see) {
see.printStackTrace();
}
}
}
return postFix;
}