Question

The code below accepts and evaluates an integer expression with the following operators: +, _, *,...

  1. The code below accepts and evaluates an integer expression with the following operators: +, _, *, and /. Your task is to modify it to include the % remainder operator that has the same precedence as * and /. No need to rewrite the entire program, just insert the needed statements.

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<Integer> operandStack = new Stack<>();

    // Create operatorStack to store operators
    Stack<Character> 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<Integer> operandStack, Stack<Character> 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;
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

/* Since we know % is of same priority like * and / add the % operator wherever you are checking with / and * operator */

/* Below code is working % operator */

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<Integer> operandStack = new Stack<>();

// Create operatorStack to store operators
Stack<Character> 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() == '/')||
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) == '/' || token.charAt(i) == '%') {
// Process all *, / and % in the top of the operator stack
while (!operatorStack.isEmpty() &&
(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.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<Integer> operandStack, Stack<Character> 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);
   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) == '/' || s.charAt(i) == '%')
result += " " + s.charAt(i) + " ";
else
result += s.charAt(i);
}

return result;
}
}

/* PLEASE UPVOTE (THANK YOU IN ADVANCE ) IF YOU SATISFY WITH THE ANSWER. IF ANY QUERY ASK ME IN COMMENT SECTION I WILL RE-SOLVE THE QUESTION FOR YOU */

Add a comment
Know the answer?
Add Answer to:
The code below accepts and evaluates an integer expression with the following operators: +, _, *,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hello, please correct the following C++ CODE it is not working on visual studio: (I WILL RATE, NO...

    Hello, please correct the following C++ CODE it is not working on visual studio: (I WILL RATE, NO INCOMPLETE OR WRONG SOLUTIONS PLEASE) // CPP program to evaluate a given // expression where tokens are // separated by space. #include using namespace std; // Function to find precedence of // operators. int precedence(char op){ if(op == '+'||op == '-') return 1; if(op == '*'||op == '/') return 2; return 0; } // Function to perform arithmetic operations. int applyOp(int a,...

  • Here is the code I have so far. I'm trying to figure out how to implement...

    Here is the code I have so far. I'm trying to figure out how to implement a boolean and use precedence. The 2nd expression should be 14 but it comes out as 28 so I'm definitely not understanding. #include <stack> #include <iostream> #include <string> using namespace std; // Function to find precedence of // operators. int precedence(char op) {    if (op == '+' || op == '-')        return 1;    if (op == '*' || op ==...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • I'm getting errors that i can't figure out. I need help fixing them. particularly focus on...

    I'm getting errors that i can't figure out. I need help fixing them. particularly focus on the errors they are highlighted in bold on the list code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include "stack.h" #include "booleanEvaluation.h" #include "booleanWithError.h" /* evaluatePostfix * input: a postfix expression * output: T, F, or E * * Uses a stack to evaluates the postfix expression and returns the result as a string where "T" denotes true and "F" denotes...

  • This code in C converts infix to postfix and evaluates it. The problem is that it...

    This code in C converts infix to postfix and evaluates it. The problem is that it only evaluates one digit expressions. I need to fix it so that it can evaluate 2 digits expressions as well. #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> #define SIZE 100 char s[SIZE]; int top=-1; void infixToPostfix(char *infix, char *postfix); void postfixEvaluation(char *postfix); void push(char elem){ s[++top]=elem; } char pop(){ return(s[top--]); } int pr(char elem){ // Order of precedence switch (elem) { case '(':...

  • Evaluateeg EvaluateInFix.java: import java.util.Stack; import java.util.Scanner; public class EvaluateInfix {    public static void main(String[] args)...

    Evaluateeg EvaluateInFix.java: import java.util.Stack; import java.util.Scanner; public class EvaluateInfix {    public static void main(String[] args)    {    Scanner keyboard = new Scanner(System.in); System.out.println("This program an inFix Expression: "); System.out.print("Enter an inFix Expression that you want to evaluate (or enter ! to exit): "); String aString = keyboard.nextLine();    while (!aString.equals("!")) {    System.out.println (evaluateinFix(aString));    System.out.print("Enter an inFix Expression that you want to evaluate (or enter ! to exit): ");    aString = keyboard.nextLine(); } // end while...

  • I'm having trouble writing this code, can some help me? Step 1: Capturing the input The...

    I'm having trouble writing this code, can some help me? Step 1: Capturing the input The first step is to write a functionGetInput()that inputs the expression from the keyboard and returns the tokens---the operands and operators---in a queue. You must write this function. To make the input easier to process, the operands and operators will be separated by one or more spaces, and the expression will be followed by #. For example, here’s a valid input to your program: 6...

  • Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)   ...

    Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)    at InfixExpression.Evaluate(InfixExpression.java:65)    at InfixExpression.setWholeExpr(InfixExpression.java:24)    at InfixExpression.<init>(InfixExpression.java:17)    at Main.testHW1(Main.java:17)    at Main.main(Main.java:6)" I need to get this as my output: "Testing InfixExpression: When passing null, the String and double = Infix String: , result: 0.0 When passing a valid String, the String and double = Infix String: ( 234.5 * ( 5.6 + 7.0 ) ) / 100.2, result: 29.488023952095805 ..." I...

  • 10. What prints when the following code is executed? public static void main (String args) "Cattywampus"; for (...

    10. What prints when the following code is executed? public static void main (String args) "Cattywampus"; for (int i-s.length )-1 i> 0 i-2) if (s.charAt (i)a') System.out.print(""); ] else if (s.charAt (i)'t') System.out.print (s.charAt (i-2)) i+ti else System. out. print (s . charAt (İ) ) ; if (i<2) System.out.print ("y"); System.out.println () 10. What prints when the following code is executed? public static void main (String args) "Cattywampus"; for (int i-s.length )-1 i> 0 i-2) if (s.charAt (i)a') System.out.print(""); ]...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT