implement a class of infix calculators. Consider simple infix expressionthat con
ID: 3726982 • Letter: I
Question
implement a class of infix calculators.
Consider simple infix expressionthat 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 of infix calculators. Use the algorithms given in the chapter 6 to evaluate infix expressions as entered into the calculator. You must first convert the infix expression to postfix form and then evaluate the resulting postfix expression.
You need to implement a driver function that takes one line of infix expression either from console or an input file infix.dat, and print out the post fix expression and calculated result to the console.
Explanation / Answer
/* program to convert infix expression to postfix*/
import java.util.Stack;
import java.util.Scanner;
public class Infix {
static int Precedence(char c)
{
switch (c)
{
case '+':return 1;
case '-':return 1;
case '*':return 2;
case '/':return 2;
case '^':return 3;
}
return -1;
}
static String inToPost(String exp)
{
String result = new String("");
// initialization of empty stack
Stack<Character> st = new Stack<>();
for (int i = 0; i<exp.length(); i++)
{
char c = exp.charAt(i);
if (Character.isLetterOrDigit(c))
result += c;
// If the scanned character is an '(', push it onto the stack.
else if (c == '(')
st.push(c);
// If the scanned character is an ')', pop and output from the stack until an '(' is encountered.
else if (c == ')')
{
while (!st.isEmpty() && st.peek() != '(')
result += st.pop();
if (!st.isEmpty() && st.peek() != '(')
return "expression is invalid";
else
st.pop();
}
else // if an operator is encountered
{
while (!st.isEmpty() && Precedence(c) <= Precedence(st.peek()))
result += st.pop();
st.push(c);
}
}
// pop all the operators from the stack
while (!st.isEmpty())
result += st.pop();
return result;
}
static int evaluate(String exp)
{
Stack<Integer> st=new Stack<>();
// Scan all characters one by one
for(int i=0;i<exp.length();i++)
{
char c=exp.charAt(i);
// If the scanned character is an integer,
// push it to the stack.
if(Character.isDigit(c))
st.push(c - '0');//coverting character to integer then pushing into the stack
// If the scanned character is an operator, pop two elements from stack apply the operator
else
{
int val1 = st.pop();
int val2 = st.pop();
switch(c)
{
case '+':
st.push(val2+val1);
break;
case '-':
st.push(val2- val1);
break;
case '/':
st.push(val2/val1);
break;
case '*':
st.push(val2*val1);
break;
}
}
}
return st.pop();
}
public static void main(String[] args)
{
String exp;
Scanner sc=new Scanner(System.in);
exp=sc.nextLine();
System.out.println(inToPost(exp));
System.out.println(evaluate(inToPost(exp)));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.