Question
Hi I am working of Java InfixtToPostfixConverstion algorithm and I followed the exact syntax in textbook but when I am testing my output I am
Hi
I am working of Java InfixtToPostfixConverstion algorithm and I followed the exact syntax in textbook but when I am testing my output I am getting the same input which means my converter doesn't work. Can you help me to figure out what is wrong in this code which is just copied from a textbook( Assignment is about using SinglyLinkedStack to solve this problem which I used my stack in other assignments and works with no issues).
here is my code:
package InfixToPostFixConversion; import java.util.*; import Palindrome.LinkedStack;
public class InfixToPostfix { private static final String operators="+-*/"; private static final int[]precedence= {1,1,2,2}; private LinkedStack
private static String convert(String infix)throws SyntaxErrorException { InfixToPostfix infixToPostFix=new InfixToPostfix(); infixToPostFix.convertToPostfix(infix); return infixToPostFix.getPostfix(); } public void convertToPostfix(String infix) throws SyntaxErrorException{ String []tokens=infix.split("\\s+"); try { for (String token:tokens) { char firstChar=token.charAt(0); if(Character.isJavaIdentifierPart(firstChar) || Character.isDigit(firstChar)) { postfix.append(token); } else if(isOperator(firstChar)) { processOperator(firstChar); } else { throw new SyntaxErrorException("Unexpected Character Encountered: "+firstChar); } } while (!operatorStack.isEmpty()) { char op=operatorStack.pop(); postfix.append(op); } } catch(NoSuchElementException ex) { throw new SyntaxErrorException("Syntax error: the stack is Empty"); } }
private static boolean isOperator(char op) { return operators.indexOf(op)!=-1; } private static int precedence(char op) { return precedence[operators.indexOf(op)]; } private void processOperator(char op) { if(operatorStack.isEmpty()) { operatorStack.push(op); } else { char topOp=operatorStack.peek(); if(precedence(op)>precedence(topOp)) { operatorStack.push(op); } else { while(!operatorStack.isEmpty() && precedence(op)<=precedence(topOp)) { operatorStack.pop(); postfix.append(topOp); if(!operatorStack.isEmpty()) { topOp=operatorStack.peek(); } } operatorStack.push(op); } } } public static void main(String[] args) throws SyntaxErrorException { InfixToPostfix p= new InfixToPostfix(); p.convertToPostfix("a+b");
// output is a+b }
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started