Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

DO MOT HARD CODE ANYTHING! These are sample answers below. Your code must have t

ID: 3863663 • Letter: D

Question

DO MOT HARD CODE ANYTHING!

These are sample answers below. Your code must have the answers like that.

Infix:

(3 * 4 - (2 + 5)) * 4 / 2 = valid expression

10 + 6 * 11 -(3 * 2 + 14) / 2 = valid expression

Postfix:

9 3 / 6 / 4 * 10 - = -8

9 3 / 6 / 4 * -10 - = 12

Question:

(a) Using java.util.stack to write a java program to validate and calculate the result of each arithmetic Expression from input file (infix.dat). All equations from the input file are in traditional infix notation. Display each expression first. Then, if the arithmetic expression is not valid, display “Invalid expression ”message and display the result of the calculation.

(b) Using java.util.Stack and java.util.StringTokenizer to write a java program to validate and calculate postfix expression from the input data file - postfix.dat

infix.dat

5 * 6 + 4
3 - 2 +
( 3 * 4 - (2 + 5)) * 4 / 2
10 + 6 * 11 -(3 * 2 + 14) / 2
2 * (12 + (3 + 5 ) * 2

postfix.dat

5 2 + 8 5 - *
2 4 - 5 2 * +
5 2 6 3 - * + 4 + 2 3 1 + * 7
5 0 /
9 3 / 6 / 4 * 10 - 3 / +
9 3 / 6 / 4 * 10 -
5 2 6 3 - * + 4 + 2 3 1 + * 7 - *
9 3 / 6 / 4 * -10 -

Explanation / Answer

package chegg;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
import java.util.Stack;

public class InfixAndPosfixExpressionEvaluation {

   public static int infixEvaluation(String expression) throws Exception {

       char[] tokens = expression.toCharArray();

       Stack<Integer> values = new Stack<Integer>();

       Stack<Character> ops = new Stack<Character>();

       for (int i = 0; i < tokens.length; i++) {
           // Current token is a whitespace, skip it
           if (tokens[i] == ' ')
               continue;
           if (tokens[i] >= '0' && tokens[i] <= '9') {
               StringBuffer sbuf = new StringBuffer();
               while (i < tokens.length && tokens[i] >= '0'
                       && tokens[i] <= '9')
                   sbuf.append(tokens[i++]);
               values.push(Integer.parseInt(sbuf.toString()));
           }

           else if (tokens[i] == '(')
               ops.push(tokens[i]);

           // Closing brace encountered, solve entire brace
           else if (tokens[i] == ')') {
               while (ops.peek() != '(')
                   values.push(applyArithmaticOp(ops.pop(), values.pop(),
                           values.pop()));
               ops.pop();
           }

           // Current token is an operator.
           else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*'
                   || tokens[i] == '/') {
               while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
                   values.push(applyArithmaticOp(ops.pop(), values.pop(),
                           values.pop()));

               // Push current token to 'ops'.
               ops.push(tokens[i]);
           }
       }

       try {
           // Entire expression has been parsed at this point, apply remaining
           // ops to remaining values
           while (!ops.empty())
               values.push(applyArithmaticOp(ops.pop(), values.pop(),
                       values.pop()));
       } catch (EmptyStackException e) {
           throw new Exception("Invalid expression");
       }

       // Top of 'values' contains result, return it
       return values.pop();
   }

   // Returns true if 'op2' has higher or same precedence as 'op1',
   // otherwise returns false.
   public static boolean hasPrecedence(char op1, char op2) {
       if (op2 == '(' || op2 == ')')
           return false;
       if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
           return false;
       else
           return true;
   }

   // A utility method to apply an operator 'op' on operands 'a'
   // and 'b'. Return the result.
   public static int applyArithmaticOp(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;
   }

   public static void main(String[] args) {
  
           List<String> expressionList = readFile(new File("d:\infix.dat.txt"));
          
           for (String expression : expressionList) {
               try {
                   int result = InfixAndPosfixExpressionEvaluation.infixEvaluation(expression);
                   System.out.println("expression result "+ result + " ");
               } catch (Exception e) {
                   System.out.println(e.getMessage());
               }
           }
          
       }

   private static List<String> readFile(File fileName) {
       List<String> expression = new ArrayList<String>();
       try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
           String sCurrentLine;
           while ((sCurrentLine = br.readLine()) != null) {
               expression.add(sCurrentLine);
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
       return expression;

   }
}

Input : suppose following expression are mentioned in file

100 * ( 2 + 12
3 + ( 5 *3 )

Output ;

Invalid expression

expression result 18