in JAVA, I need to make the following code from infix to postfix for 2 stacks in
ID: 3782186 • Letter: I
Question
in JAVA, I need to make the following code from infix to postfix for 2 stacks in order to calculate such as (2+3*5)-8/5*(5-2).
The following code is to calculate only 1 stack such as 12/(1+11)*2.
=====================================================================================
import java.util.*;
public class Practice {
public static int evaluate(String expression){
char[] tokens = expression.toCharArray();
* // Stack for numbers
Stack<Integer> operandStack = new Stack<Integer>();
// Stack for Operators
Stack<Character> operatorStack = new Stack<Character>();
//using for is more natural here
for (int i = 0; i < tokens.length; i++)
{
if (tokens[i] == ' ')
continue;
// Token is a number, push it to stack
if (tokens[i] >= '0' && tokens[i] <= '9')
{
// There can be multi digit number. Create number as sring
StringBuffer numberString = new StringBuffer();
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
{
numberString.append(tokens[i++]);
}
// Converting numberString to integer and adding to array
operandStack.push(Integer.parseInt(numberString.toString()));
}
// Encounter open bracket, push it to operator stack
else if (tokens[i] == '(')
operatorStack.push(tokens[i]);
// Encounter closing bracket, evaluate and push result back in operand stack
else if (tokens[i] == ')')
{
while (operatorStack.peek() != '(')
operandStack.push(evaluateOpeartion(operatorStack.pop(), operandStack.pop(), operandStack.pop()));
operatorStack.pop();
}
// Encounter a operator
else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/')
{
while (!operatorStack.empty() &&
isHigherPrecedence(tokens[i], operatorStack.peek()))
{
operandStack.push(evaluateOpeartion(operatorStack.pop(), operandStack.pop(), operandStack.pop()));
}
// Push current token to 'ops'.
operatorStack.push(tokens[i]);
}
}
while (!operatorStack.empty())
operandStack.push(evaluateOpeartion(operatorStack.pop(), operandStack.pop(), operandStack.pop()));
// operandStack now contain result
return operandStack.pop();
}
// check for precendence order
public static boolean isHigherPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// Evaluate result of operator on operand b and a
public static int evaluateOpeartion(char op, int b, int a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
// Test result
public static void main(String[] args)
{
System.out.println(Practice.evaluate("900 / 10 * 2 + 6"));
System.out.println(Practice.evaluate("12 / ( 1 + 11 ) * 2"));
System.out.println(Practice.evaluate("(2+3*5)-8/5*(5-2)"));
}
}
Explanation / Answer
// Folowing code is able to handle the expression you mentioned and it is using two stacks.
// If I am missing anything please update your question or clarify it in comment and I would be happy to refine my code.
import java.util.Stack;
public class Evaluation
{
public static int evaluate(String expression)
{
char[] tokens = expression.toCharArray();
// Stack for numbers
Stack<Integer> operandStack = new Stack<Integer>();
// Stack for Operators
Stack<Character> operatorStack = new Stack<Character>();
//using for is more natural here
for (int i = 0; i < tokens.length; i++)
{
if (tokens[i] == ' ')
continue;
// Token is a number, push it to stack
if (tokens[i] >= '0' && tokens[i] <= '9')
{
// There can be multi digit number. Create number as sring
StringBuffer numberString = new StringBuffer();
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
{
numberString.append(tokens[i++]);
}
// Converting numberString to integer and adding to array
operandStack.push(Integer.parseInt(numberString.toString()));
}
// Encounter open bracket, push it to operator stack
else if (tokens[i] == '(')
operatorStack.push(tokens[i]);
// Encounter closing bracket, evaluate and push result back in operand stack
else if (tokens[i] == ')')
{
while (operatorStack.peek() != '(')
operandStack.push(evaluateOpeartion(operatorStack.pop(), operandStack.pop(), operandStack.pop()));
operatorStack.pop();
}
// Encounter a operator
else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/')
{
while (!operatorStack.empty() &&
isHigherPrecedence(tokens[i], operatorStack.peek()))
{
operandStack.push(evaluateOpeartion(operatorStack.pop(), operandStack.pop(), operandStack.pop()));
}
// Push current token to 'ops'.
operatorStack.push(tokens[i]);
}
}
while (!operatorStack.empty())
operandStack.push(evaluateOpeartion(operatorStack.pop(), operandStack.pop(), operandStack.pop()));
// operandStack now contain result
return operandStack.pop();
}
// check for precendence order
public static boolean isHigherPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// Evaluate result of operator on operand b and a
public static int evaluateOpeartion(char op, int b, int a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
// Test result
public static void main(String[] args)
{
System.out.println(Evaluation.evaluate("900 / 10 * 2 + 6"));
System.out.println(Evaluation.evaluate("12 / ( 1 + 11 ) * 2"));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.