Please write a clear solution and comments for this Data str

Please, write a clear solution and comments for this Data structures problems.

Implement a program in Java to convert an infix expression that includes (, ), +, -, *, and/to postfix expression. For simplicity, your program will read from standard input (until the user enters the symbol \"=\") an infix expression of single lower case and the operators +, -, /, *, and (), and output a postfix expression.

Solution

Program:

import java.util.Stack;
import java.util.Scanner;

public class InfixToPostfix {
static private String expression;
private Stack<Character> stack = new Stack<Character>();
   private static Scanner sca;

public InfixToPostfix(String infixExpression) {
expression = infixExpression;
}

public String infixToPostfix() {
String postfixString = \"\";

for (int index = 0; index < expression.length(); ++index) {
char value = expression.charAt(index);
if (value == \'(\') {
stack.push(\'(\');
} else if (value == \')\') {
Character oper = stack.peek();

while (!(oper.equals(\'(\')) && !(stack.isEmpty())) {
stack.pop();
postfixString += oper.charValue();
if (!stack.isEmpty())
oper = stack.peek(); // Code Added
}
stack.pop();
} else if (value == \'+\' || value == \'-\') {
if (stack.isEmpty()) {
stack.push(value);
} else {
Character oper = stack.peek();
while (!(stack.isEmpty() || oper.equals((\'(\')) || oper.equals((\')\')))) {
oper = stack.pop();
postfixString += oper.charValue();
}
stack.push(value);
}
} else if (value == \'*\' || value == \'/\') {
if (stack.isEmpty()) {
stack.push(value);
} else {
Character oper = stack.peek();
while (!oper.equals((\'(\')) && !oper.equals((\'+\')) && !oper.equals((\'-\')) && !stack.isEmpty()) {
oper = stack.pop();
postfixString += oper.charValue();
}
stack.push(value);
}
} else {
postfixString += value;
}
}

while (!stack.isEmpty()) {
Character oper = stack.peek();
if (!oper.equals((\'(\'))) {
stack.pop();
postfixString += oper.charValue();
}
}
return postfixString;
}

public static void main(String[] str) {
System.out.println(\"Enter infix expression : \");
sca = new Scanner(System.in);
String infixExpression = sca.next();
InfixToPostfix obj = new InfixToPostfix(infixExpression);
System.out.println(\"Postfix Expression : \ \" + obj.infixToPostfix());
}
}

Result:

Enter infix expression :
(1+6)*5
Postfix Expression :
16+5*

Please, write a clear solution and comments for this Data structures problems. Implement a program in Java to convert an infix expression that includes (, ), +,
Please, write a clear solution and comments for this Data structures problems. Implement a program in Java to convert an infix expression that includes (, ), +,

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site