Hello All,
I am trying to implement a program that takes a prefix expression/string and converts it into a postfix string. I looked up the general algorithim for this converson and tried to implement it myself into this program. The following code is taken from my main java file. My output is displaying only the characters, not any of the operators in their correct place.
Example, I have '+abc' and the correct output should be 'ab+c'. In this case my current output reads as 'abc'. Any help would be appreciated. Code is below:
public class PreToPostPrac {
public static void main(String[] args) {
String s1 = "*+abc";
String s2 = "+-ab*-cde";
String s3 = "+*-ab-*cd*ef-gh";
String s4 = "-*+a-bc*+def-/gh*k1";
// System.out.printf("Prefix: %s\nPostfix: %s\n\n", s1,preToPost(s1));
System.out.printf("Prefix: %s\nPostfix: %s\n\n", s2,preToPost(s2));
// System.out.printf("Prefix: %s\nPostfix: %s\n\n", s3,preToPost(s3));
// System.out.printf("Prefix: %s\nPostfix: %s\n\n", s4,preToPost(s4));
}
public static String preToPost(String infix) {
char curChar;
int infixLength = infix.length();
String postFix = "";
CharStackPrac newStack = new CharStackPrac(infixLength);
for (int x = 0; x < infix.length(); x++) {
curChar = infix.charAt(x);
if (isOperator(curChar) == true) {
newStack.push(curChar);
} else {
if (isOperator(curChar) == false)
postFix = postFix + curChar;
while (!newStack.isEmpty() && newStack.peek() == curChar) {
newStack.pop();
postFix = postFix + newStack.pop();
newStack.pop();
}
newStack.push(curChar);
}
}
return postFix;
}
public static boolean isOperator(char Op) {
if (Op == '+' || Op == '-' || Op == '*' || Op == '/') {
return true;
} else {
return false;
}
}
}