Java Modify Listing 20.9 EvaluateExpression.java to add operators ^ for exponent
ID: 3762661 • Letter: J
Question
Java
Modify Listing 20.9 EvaluateExpression.java to add
operators ^ for exponent and % for modulus. For example, 3 ^ 2 is 9 and 3 % 2
is 1. The ^ operator has the highest precedence and the % operator has the same
precedence as the * and / operators. Your program should prompt the user to
enter an expression.
Here is a sample run of the program:
Enter an expression: (5 * 2 ^ 3 + 2 * 3 % 2) * 4
(5 * 2 ^ 3 + 2 * 3 % 2) * 4 = 160
-----------------------------------------------------------------------------
20.9
-----------------------------------------------------------------------------
import java.util.Stack;
public class EvaluateExpression {
public static void main(String[] args) {
// Check number of arguments passed
if (args.length != 1) {
System.out.println(
"Usage: java EvaluateExpression "expression"");
System.exit(1);
}
try {
System.out.println(evaluateExpression(args[0]));
}
catch (Exception ex) {
System.out.println("Wrong expression: " + args[0]);
}
}
/** Evaluate an expression */
public static int evaluateExpression(String expression) {
// Create operandStack to store operands
Stack operandStack = new Stack<>();
// Create operatorStack to store operators
Stack operatorStack = new Stack<>();
// Insert blanks around (, ), +, -, /, and *
expression = insertBlanks(expression);
// Extract operands and operators
String[] tokens = expression.split(" ");
// Phase 1: Scan tokens
for (String token: tokens) {
if (token.length() == 0) // Blank space
continue; // Back to the while loop to extract the next token
else if (token.charAt(0) == '+' || token.charAt(0) == '-') {
// Process all +, -, *, / in the top of the operator stack
while (!operatorStack.isEmpty() &&
(operatorStack.peek() == '+' ||
operatorStack.peek() == '-' ||
operatorStack.peek() == '*' ||
operatorStack.peek() == '/')) {
processAnOperator(operandStack, operatorStack);
}
// Push the + or - operator into the operator stack
operatorStack.push(token.charAt(0));
}
else if (token.charAt(0) == '*' || token.charAt(0) == '/') {
// Process all *, / in the top of the operator stack
while (!operatorStack.isEmpty() &&
(operatorStack.peek() == '*' ||
operatorStack.peek() == '/')) {
processAnOperator(operandStack, operatorStack);
}
// Push the * or / operator into the operator stack
operatorStack.push(token.charAt(0));
}
else if (token.trim().charAt(0) == '(') {
operatorStack.push('('); // Push '(' to stack
}
else if (token.trim().charAt(0) == ')') {
// Process all the operators in the stack until seeing '('
while (operatorStack.peek() != '(') {
processAnOperator(operandStack, operatorStack);
}
operatorStack.pop(); // Pop the '(' symbol from the stack
}
else { // An operand scanned
// Push an operand to the stack
operandStack.push(new Integer(token));
}
}
// Phase 2: process all the remaining operators in the stack
while (!operatorStack.isEmpty()) {
processAnOperator(operandStack, operatorStack);
}
// Return the result
return operandStack.pop();
}
/** Process one operator: Take an operator from operatorStack and
* apply it on the operands in the operandStack */
public static void processAnOperator(
Stack operandStack, Stack operatorStack) {
char op = operatorStack.pop();
int op1 = operandStack.pop();
int op2 = operandStack.pop();
if (op == '+')
operandStack.push(op2 + op1);
else if (op == '-')
operandStack.push(op2 - op1);
else if (op == '*')
operandStack.push(op2 * op1);
else if (op == '/')
operandStack.push(op2 / op1);
}
public static String insertBlanks(String s) {
String result = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == ')' ||
s.charAt(i) == '+' || s.charAt(i) == '-' ||
s.charAt(i) == '*' || s.charAt(i) == '/')
result += " " + s.charAt(i) + " ";
else
result += s.charAt(i);
}
return result;
}
}
Explanation / Answer
/*
* Java Program to Evaluate an Expression using Stacks
*/
import java.util.*;
public class EvaluateExpressionUsingStacks
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Create stacks for operators and operands */
Stack<Integer> op = new Stack<Integer>();
Stack<Double> val = new Stack<Double>();
/* Create temporary stacks for operators and operands */
Stack<Integer> optmp = new Stack<Integer>();
Stack<Double> valtmp = new Stack<Double>();
/* Accept expression */
System.out.println("Evaluation Of Arithmetic Expression Using Stacks Test ");
System.out.println("Enter expression ");
String input = scan.next();
input = "0" + input;
input = input.replaceAll("-","+-");
/* Store operands and operators in respective stacks */
String temp = "";
for (int i = 0;i < input.length();i++)
{
char ch = input.charAt(i);
if (ch == '-')
temp = "-" + temp;
else if (ch != '+' && ch != '*' && ch != '/')
temp = temp + ch;
else
{
val.push(Double.parseDouble(temp));
op.push((int)ch);
temp = "";
}
}
val.push(Double.parseDouble(temp));
/* Create char array of operators as per precedence */
/* -ve sign is already taken care of while storing */
char operators[] = {'/','*','+'};
/* Evaluation of expression */
for (int i = 0; i < 3; i++)
{
boolean it = false;
while (!op.isEmpty())
{
int optr = op.pop();
double v1 = val.pop();
double v2 = val.pop();
if (optr == operators[i])
{
/* if operator matches evaluate and store in temporary stack */
if (i == 0)
{
valtmp.push(v2 / v1);
it = true;
break;
}
else if (i == 1)
{
valtmp.push(v2 * v1);
it = true;
break;
}
else if (i == 2)
{
valtmp.push(v2 + v1);
it = true;
break;
}
}
else
{
valtmp.push(v1);
val.push(v2);
optmp.push(optr);
}
}
/* Push back all elements from temporary stacks to main stacks */
while (!valtmp.isEmpty())
val.push(valtmp.pop());
while (!optmp.isEmpty())
op.push(optmp.pop());
/* Iterate again for same operator */
if (it)
i--;
}
System.out.println(" Result = "+val.pop());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.