Question
Please can someone help me with this code. postfixToprefix output is not corrct when I compile the code. It display the operand and no operator.
Please can someone help me with this code. postfixToprefix output is not corrct when I compile the code. It display the operand and no operator. here is the code.
package gui;
import java.util.Stack;
class prefixToPostFix {
private static String prefixToPostfixConversion(String prefixExp) {
final String LEFT_DONE = "LEFTDONE";
Stack
StringBuilder strPostfix = new StringBuilder();
if (prefixExp.trim().isEmpty()) {
return null;
}
char[] chars = prefixExp.toCharArray();
for (char aChar : chars) {
if (isOperator(aChar)) {
operatorStack.push(String.valueOf(aChar));
//System.out.println("aChar = " + aChar);
} else {
System.out.println("h");
strPostfix.append(String.valueOf(aChar));
while (!operatorStack.empty() && !operatorStack.peek().equals(LEFT_DONE)) {
String c=operatorStack.pop();
System.out.println("c = " + c);
strPostfix.append(c);
}
operatorStack.push("LEFTDONE");
}
}
return strPostfix.toString();
}
private static boolean isOperator(char c) {
char[] operators = { '+', '-', '/', '*'};
boolean isOp = false;
for (char operator : operators) {
if (c == operator) {
isOp = true;
break;
}
}
return isOp;
}
public String look(String calculation) {
return prefixToPostfixConversion(calculation);
}
}
class postFixToPrefix {
//function to check if character is operator or not
public boolean isOperator1(char x) {
switch (x) {
case '+':
case '-':
case '/':
case '*':
return true;
}
return false;
}
// convert postfix to prefix expression
public String postfixToPrefix(String post_exp) {
Stack
//length of expression
int length = post_exp.length();
// reading from right to left
for (int i = 0; i < length; i++) {
// check if symbol is operator
if (isOperator1(post_exp.charAt(i))) {
//pop two operands from stack
String op1 = s.peek();
s.pop();
String op2 = s.peek();
s.pop();
//concat the operands and operator
String temp = post_exp.charAt(i) + op2 + op1;
//push string temp back to stack
s.push(temp);
}
// if symbol is an operand
else {
//push the operand to the stack
s.push(String.valueOf(post_exp.charAt(i)));
}
}
// stack[0] contains the prefix expression
return s.peek();
}
//Driver Code
public String look(String calculation) {
return postfixToPrefix(calculation);
}
}
class DivideByZero extends Exception {
// A constructor that reads the message
DivideByZero(String message) {
super(message);
}
}
class InvalidCharacterException extends Exception {
// Constructor
InvalidCharacterException() {
}
}
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