These are sample answers below. Your code must have the answers like that. Infix
ID: 3810363 • Letter: T
Question
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
Ans: The following two program gives required output and explained clearly with comments
(a). import java.io.*;
import java.util.stack;
// stack class
class Stack
{
char a[]=new char[100];
int top=-1;
void push(char c)
{
// exception
try
{
a[++top]= c;
}
//if StrigngIndexOutOfBoundsException
catch(StringIndexOutOfBoundsException e)
{
// if yes prints stack if full
System.out.println("Stack is full , there is no room to push , size=100");
// exits
System.exit(0);
}
}
// pop
char pop()
{
// returns
return a[top--];
}
// boolean isEmpty
boolean isEmpty()
{
// returns boolean by the condition
return (top==-1)?true:false;
}
// peek()
char peek()
{
// top
return a[top];
}
}
// class InfixToPostfix
public class InfixToPostfix
{
static Stack operators = new Stack();
public static void main(String argv[]) throws IOException
{
String infix;
// BufferReader for readng values
BufferedReader keyboard = new BufferedReader (new InputStreamReader(System.in));
// for taking user input
System.out.print(" Enter algebriac expression in infix: ");
// keyboard
infix = keyboard.readLine();
// gives postix
System.out.println("Expression in the postfix :" + toPostfix(infix));
}
// for infix to postfix toPostfix()
private static String toPostfix(String infix)
{
char symbol;
String postfix = "";
for(int i=0;i<infix.length();++i)
{
// as input is there
// infix.charAt(i)
symbol = infix.charAt(i);
//if it's an operand, add it to the string
if (Character.isLetter(symbol))
postfix = postfix + symbol;
else if (symbol=='(')
/(
{
// to push
operators.push(symbol);
}
//else
else if (symbol==')')
(
{
// operators.peek()
while (operators.peek() != '(')
{
postfix = postfix + operators.pop();
}
// for removing
operators.pop(); '('
}
else
{
// calcultation here using prec(peek)
while (!operators.isEmpty() && !(operators.peek()=='(') && prec(symbol) <= prec(operators.peek()))
postfix = postfix + operators.pop();
operators.push(symbol);
}
}
// if operator is empty
while (!operators.isEmpty())
postfix = postfix + operators.pop();
return postfix;
}
static int prec(char x)
{
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/' || x == '%')
return 2;
return 0;
}
}
(b). import java.util.Stack; // importing stack
// Class EvaluateString
public class EvaluateString
{
public static int evaluate(String expression)
{
char[] tokens = expression.toCharArray();
// numbers
Stack<Integer> values = new Stack<Integer>();
// operators
Stack<Character> ops = new Stack<Character>();
for (int i = 0; i < tokens.length; i++)
{
// Current token is a whitespace, skip it
if (tokens[i] == ' ')
// continues
continue;
// if present token is number then push to stack for the numbers
if (tokens[i] >= '0' && tokens[i] <= '9')
{
StringBuffer sbuf = new StringBuffer();
// is there is above 1 digit numbers
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
// append
sbuf.append(tokens[i++]);
values.push(Integer.parseInt(sbuf.toString()));
}
// present token is opening brace push to ops
else if (tokens[i] == '(')
// push
ops.push(tokens[i]);
// Closing brace encountered, solve entire brace
else if (tokens[i] == ')')
{
while (ops.peek() != '(')
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
ops.pop();
}
// Current token is an operator.
else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/')
{
//if ops not empty
while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Push current token to 'ops'.
ops.push(tokens[i]);
}
}
while (!ops.empty())
// push values()
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Top of values contains result return it
return values.pop();
}
public static boolean hasPrecedence(char op1, char op2)
{
// op conditions
if (op2 == '(' || op2 == ')')
// false
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
// returns true
return true;
}
// for applying on the operands
public static int applyOp(char op, int b, int a)
{
switch (op)
{
// case for addition +
case '+':
return a + b;
// case for substraction -
case '-':
return a - b;
// case for multiplication *
case '*':
return a * b;
// case for division /
case '/':
if (b == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
// exception case
return a / b;
}
// returns 0
return 0;
}
public static void main(String[] args)
{
System.out.println(EvaluateString.evaluate("52 + 85"));
System.out.println(EvaluateString.evaluate("24 - 52"));
System.out.println(EvaluateString.evaluate("5263 * ( 4 + 231 ) * 7"));
System.out.println(EvaluateString.evaluate("50"));
System.out.println(EvaluateString.evaluate("93 / 6 / 4 *(10-3)");
System.out.println(EvaluateString.evaluate("93 / 6 / 4 *(10)");
System.out.println(EvaluateString.evaluate("526 * (4+231) * 7"));
System.out.println(EvaluateString.evaluate("93 / 6 / 4 * (10)"));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.