aUsing javautilstack to write a java program to validate and
(a)Using java.util.stack to write a java program to validate and calculate the result of each arithmetic Expression from input file (infix.txt). 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 otherwise display the result of the calculation. (2 points)
(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 (2 points)
infile.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.txt
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 -
Solution
Java Code
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* A Java program to evaluate a infix expression where tokens are separated by space.
* Test Cases:
* 1. 5 * 6 + 4
* 2. 3 - 2 +
* 3. ( 3 * 4 - (2 + 5)) * 4 / 2
* 4. 10 + 6 * 11 -(3 * 2 + 14) / 2
* 5. 2 * (12 + (3 + 5 ) * 2
*/
import java.util.Stack;
public class InfixEvaluator {
public static int computeInfix(String expression) {
char[] tokens = expression.toCharArray();
Stack<Integer> oprands = new Stack<Integer>();
Stack<Character> oprators = new Stack<Character>();
for (int i = 0; i < tokens.length; i++) {
// Token is a whitespace, skip it
if (tokens[i] == \' \')
continue;
// Token is a number, push it to stack for numbers
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++]);
oprands.push(Integer.parseInt(sbuf.toString()));
}
// Token is an opening brace, push it to \'ops\'
else if (tokens[i] == \'(\')
oprators.push(tokens[i]);
// Closing brace encountered, solve entire brace
else if (tokens[i] == \')\') {
while (oprators.peek() != \'(\')
oprands.push(applyOperator(oprators.pop(), oprands.pop(), oprands.pop()));
oprators.pop();
}
// Token is an operator.
else if (tokens[i] == \'+\' || tokens[i] == \'-\' || tokens[i] == \'*\' || tokens[i] == \'/\') {
while (!oprators.empty() && precedenceOrder(tokens[i], oprators.peek()))
oprands.push(applyOperator(oprators.pop(), oprands.pop(), oprands.pop()));
// Push current token to \'ops\'.
oprators.push(tokens[i]);
}
}
while (!oprators.empty())
oprands.push(applyOperator(oprators.pop(), oprands.pop(), oprands.pop()));
return oprands.pop();
}
/**
* precedenceOrder
*
* @param oprator1
* @param oprator
* @return
*/
public static boolean precedenceOrder(char oprator1, char oprator) {
if (oprator == \'(\' || oprator == \')\')
return false;
if ((oprator1 == \'*\' || oprator1 == \'/\') && (oprator == \'+\' || oprator == \'-\'))
return false;
else
return true;
}
/**
* applyOperator
*
* @param oprator
* @param oprend1
* @param oprand2
* @return
*/
public static int applyOperator(char oprator, int oprend1, int oprand2) {
switch (oprator) {
case \'+\':
return oprand2 + oprend1;
case \'-\':
return oprand2 - oprend1;
case \'*\':
return oprand2 * oprend1;
case \'/\':
if (oprend1 == 0)
throw new UnsupportedOperationException(\"Cannot divide by zero\");
return oprand2 / oprend1;
}
return 0;
}
// Driver method to test above methods
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
File file = new File(\"/home/ramesh/infix.dat\");
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.print(line + \" = \");
try {
System.out.println(InfixEvaluator.computeInfix(line));
} catch (UnsupportedOperationException exception) {
System.out.println(\"Error:\" + exception.getMessage());
} catch (Exception exception) {
System.out.println(\"Invalid expression\");
}
}
} catch (IOException exception) {
System.out.println(\"Error: \" + exception.getMessage());
} finally {
if (fileReader != null)
try {
fileReader.close();
} catch (IOException e) {
System.out.println(\"Error: IO\");
}
if (bufferedReader != null)
try {
bufferedReader.close();
} catch (IOException e) {
System.out.println(\"Error: IO\");
}
}
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
import java.util.StringTokenizer;
/**
* A Java program to evaluate & validate a postfix expression where tokens are
* separated by space. Test Cases:
*
*/
public class PostfixEvaluator {
/**
* Validate & Evaluates a postfix expression
*
* @param postfix
* @return the integer value of the expression
* @throws InvalidExpression
*/
public static int computePostfix(String postfix) throws InvalidExpression {
Stack<Integer> stack = new Stack<Integer>();
StringTokenizer st = new StringTokenizer(postfix);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.equals(\"*\") || // An operator
token.equals(\"+\") || token.equals(\"-\") || token.equals(\"%\") || token.equals(\"/\")) {
applyOperator(token, stack);
} else { // An operand
stack.push(new Integer(token));
}
}
int result = ((Integer) stack.pop()).intValue();
if (!stack.isEmpty()) {
throw new InvalidExpression(\"Invalid expression\");
}
return result;
}
/**
* Possible operators are \"+\", \"-\", \"%\", and \"/\"
*
* @param operator
* @param stack
*/
private static void applyOperator(String operator, Stack<Integer> stack) {
int oprand1 = stack.pop();
int oprand2 = stack.pop();
int result;
if (operator.equals(\"+\")) {
result = oprand2 + oprand1;
} else if (operator.equals(\"-\")) {
result = oprand2 - oprand1;
} else if (operator.equals(\"/\")) {
if (oprand1 == 0)
throw new UnsupportedOperationException(\"Cannot divide by zero\");
result = oprand2 / oprand1;
} else if (operator.equals(\"%\")) {
result = oprand2 % oprand1;
} else if (operator.equals(\"*\")) {
result = oprand2 * oprand1;
} else {
throw new IllegalArgumentException();
}
stack.push(result);
}
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
File file = new File(\"/home/ramesh/postfix.dat\");
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.print(line + \" = \");
try {
System.out.println(PostfixEvaluator.computePostfix(line));
} catch (UnsupportedOperationException exception) {
System.out.println(\"Error:\" + exception.getMessage());
} catch (Exception exception) {
System.out.println(\"Invalid expression\");
}
}
} catch (IOException exception) {
System.out.println(\"Error: \" + exception.getMessage());
} finally {
if (fileReader != null)
try {
fileReader.close();
} catch (IOException e) {
System.out.println(\"Error: IO\");
}
if (bufferedReader != null)
try {
bufferedReader.close();
} catch (IOException e) {
System.out.println(\"Error: IO\");
}
}
}
}
@SuppressWarnings(\"serial\")
public class InvalidExpression extends Exception {
public InvalidExpression() {
super();
}
public InvalidExpression(String message) {
super(message);
}
}




