DO MOT HARD CODE ANYTHING! These are sample answers below. Your code must have t
ID: 3864445 • 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
import java.util.*;
public class EvaluateExpressionUsingStacks
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Stack<Integer> op = new Stack<Integer>();
Stack<Double> val = new Stack<Double>();
Stack<Integer> optmp = new Stack<Integer>();
Stack<Double> valtmp = new Stack<Double>();
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("-","+-");
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));
char operators[] = {'/','*','+'};
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 (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);
}
while (!valtmp.isEmpty())
val.push(valtmp.pop());
while (!optmp.isEmpty())
op.push(optmp.pop());
if (it)
i--;
}
System.out.println(" Result = "+val.pop());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.