Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Data Structures using java Chapter 7 Q 6. consider simpls infix expression that

ID: 3765108 • Letter: D

Question

Data Structures using java

Chapter 7 Q 6.

consider simpls infix expression that consist of single-digit operands; the operators +, -, *, %,/; and parentheses. assume that unary operators are illegal and that the expression contains no embedded spaces.

Desing and implement a class for an infix calculators. use the algorithm given in this chapter to convert the infix expressions to postfix form and to evaluate the resulting postfix expressions, Note that if the methods eveluate and get Postfix are called befoer the convert postfix method, then the excption illegalStateExcption should be thrown by these methods.

class Calculator {

public Calculator(String exp)

public string toString()

private boolean convertPostfix()

public String getpostfic() throws illegalStateExceptin

public int evaluate () throws illegalStateExceptin

}

You can use the PostfixCalculator class designed for Problem 4 to implement theevaluate() method of this question.

Explanation / Answer

import java.util.*;
public class InfixToPostfix
{
private boolean isOperator(char c)
{
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'|| c=='(' || c==')';
}
private boolean isSpace(char c)
{
return (c == ' ');
}
private boolean lowerPrecedence(char op1, char op2)
{
switch (op1)
{
case '+':
case '-':
return !(op2=='+' || op2=='-') ;
case '*':
case '/':
return op2=='^' || op2=='(';
case '^':
return op2=='(';
case '(':
return true;
default:
return false;
}
}
public String convertToPostfix(String infix)
{
Stack operatorStack = new Stack();
char c;
StringTokenizer parser = new StringTokenizer(infix,"+-*/^() ",true);
StringBuffer postfix = new StringBuffer(infix.length());
while (parser.hasMoreTokens())
{   
String token = parser.nextToken();   
c = token.charAt(0);   
if ( (token.length() == 1) && isOperator(c) )
{
while (!operatorStack.empty() &&!lowerPrecedence(((String)operatorStack.peek()).charAt(0), c))
postfix.append(" ").append((String)operatorStack.pop());
if (c==')')
{
String operator = (String)operatorStack.pop();
while (operator.charAt(0)!='(')
{
postfix.append(" ").append(operator);
operator = (String)operatorStack.pop();
}
}
else
operatorStack.push(token);
}
else if ( (token.length() == 1) && isSpace(c) )
{   
}
else
{
postfix.append(" ").append(token);
}
}
while (!operatorStack.empty())
postfix.append(" ").append((String)operatorStack.pop());
return postfix.toString();
}