I've been stuck on this program for about a week and I can't see what I'm doing wrong. I can't get the operands and operators to print in the proper spot and the '(' ')' won't delete. Here's what I have so far. HELP!!!
public static int precedence(char token) {
if (token == '^') {
return 1; // Lowest precedence
} else if (token == '+' || token == '-') {
return 2;
} else if (token == '*' || token == '/') {
return 3;
} else
return -1;
}
// method to convert infox => postfix
public static String infixToPostfix(String infix){
MyStackTiara<Character> operator = new MyStackTiara<>(); // 1. Create an empty stack
String postfix = ""; // Create an empty string stack
MyStackTiara<Character> noNeed = new MyStackTiara<>();
for (int i = 0; i < infix.length(); i++) {// Scan input from left to right
char token = infix.charAt(i); // Current character
if (token == '(') {
operator.push(token);
} else if (token >= '0' || token <= '9') {
// Check for operand and append to string
postfix += token;
} else if (token == ')') {
while (!operator.isEmpty()) {
if (operator.peek() == '(') {
noNeed.push(operator.pop());
break;
} else
operator.pop();
}
//operator.pop();
} else if (token == '*' || token == '/' || token == '+' || token == '-' || token == '^') {
if (token == '^') {
char op3 = operator.pop();
char operand1 = operator.pop();
char operand2 = operator.pop();
String newPostfix = postfix + operand2 + operand1 + op3;
postfix += newPostfix;
} else if (token == '+' || token == '-') {
char op2 = operator.pop();
char operand1 = operator.pop();
char operand2 = operator.pop();
String newPostfix = postfix + operand2 + operand1 + op2;
postfix += newPostfix;
} else if (token == '*' || token == '/') {
char op1 = operator.pop();
char operand1 = operator.pop();
char operand2 = operator.pop();
String newPostfix = postfix + operand2 + operand1 + op1;
postfix += newPostfix;
}
}
}
return postfix;
}
When the infix is: (4-2)*(2+3)
I want it to print: 42-23+
But it's printing: 4-2)*2+3)
token >= '0' || token <= '9'-- what exactly does that do?token >= '0' || token <= '9'check whether the token is a digit? Is it true or false whentokenis'('? What does the||operator do?