Consider simple infix expressions that consist of single-digit operands, the ope
ID: 3910556 • Letter: C
Question
Consider simple infix expressions that consist of single-digit operands, the operators +,-, *, %, and/, and parentheses. Assume that unary operators are illegal and that the expression contains no embedded spaces. Design and implement a class for an infix calculator. Use the algorithms given in this chapter to convert the infix expression to postfix form and to evaluate the resulting postfix expression. Note that if the metodsevaluate andgetPostfix are called before dieconvertPostfix mediod, then the exceptionllegalStateException should be dirown by these methods. class Calculator public Calculator(String exp) // initializes infix expression public String toString//returns infix expression private boolean convertPostfixO // creates postfix expression /l returns true if successful convertPostfix // returns the resulting postfix expression public String getPostfix0 thr Il evaluates the expression public int evaluate) throws llegalStateException>Ilend Calculator ows IllegalStateExceptionExplanation / Answer
(Ans- )
Following is the code to convert the infix expression into the postfix expression and then evaluating the postfix expression:
import java.util.Stack;
class Evaluation
{
static int check_the_precedence(char character)
{
switch (character)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
static String infix_To_Postfix_conversion(String expression)
{
String answer = new String("");
Stack<Character> st = new Stack<>();
for (int i = 0; i<expression.length(); ++i)
{
char ch = expression.charAt(i);
if (Character.isLetterOrDigit(ch))
answer += ch;
else if (ch == '(')
st.push(ch);
else if (ch == ')')
{
while (!st.isEmpty() && st.peek() != '(')
answer += st.pop();
if (!st.isEmpty() && st.peek() != '(')
return "Invalid Expression";
else
st.pop();
}
else
{
while (!st.isEmpty() && Precedence(ch) <= Precedence(st.peek()))
answer += st.pop();
st.push(ch);
}
}
while (!st.isEmpty())
answer += st.pop();
return answer;
}
static int evaluate_Postfix_expression(String expression)
{
Stack<Integer> st=new Stack<>();
for(int i=0;i<expression.length();i++)
{
char ch=expression.charAt(i);
if(Character.isDigit(ch))
st.push(ch - '0');
else
{
int value1 = st.pop();
int value2 = st.pop();
switch(ch)
{
case '+':
st.push(value2+value1);
break;
case '-':
st.push(value2- value1);
break;
case '/':
st.push(value2/value1);
break;
case '*':
st.push(value2*value1);
break;
}
}
}
return st.pop();
}
public static void main(String[] args)
{
String expression = "2+3*(2^4-6)^(31-5*6)-4";
System.out.println(evaluate_Postfix_expression(infixToPostfix(expression)));
}
}
OUTPUT:
32
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.