Question

In: Computer Science

Please make sure that these infix and postfix equations have these answers nothing else: Infix: (3...

Please make sure that these infix and postfix equations have these answers nothing else:

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

(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 otherwise 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 -

Solutions

Expert Solution

A Java program to evaluate an infix expression:

import java.util.Stack;

public class EvaluateString
{
public static int evaluate(String expression)
{
char[] tokens = expression.toCharArray();

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

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

for (int i = 0; i < tokens.length; i++)
{
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]);

else if (tokens[i] == ')')
{
while (ops.peek() != '(')
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
ops.pop();
}

else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/')
{

while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
values.push(applyOp(ops.pop(), values.pop(), values.pop()));

ops.push(tokens[i]);
}
}


while (!ops.empty())
values.push(applyOp(ops.pop(), values.pop(), values.pop()));

  
return values.pop();
}

  
public static boolean hasPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}


public static int applyOp(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;
}

A Java program to evaluate an postfix expression :

public static int postfixEvaluate(String exp) {
                Stack<Integer> s = new Stack<Integer> ();
                Scanner tokens = new Scanner(exp);
                
                while (tokens.hasNext()) {
                        if (tokens.hasNextInt()) {
                                s.push(tokens.nextInt());
                        } else {
                                int num2 = s.pop();
                                int num1 = s.pop();
                                String op = tokens.next();
                                
                                if (op.equals("+")) {
                                        s.push(num1 + num2);
                                } else if (op.equals("-")) {
                                        s.push(num1 - num2);
                                } else if (op.equals("*")) {
                                        s.push(num1 * num2);
                                } else {
                                        s.push(num1 / num2);
                                }
                                
                        }
                }
                return s.pop();
    }

Related Solutions

Make sure to write in complete sentences and realte it to children nothing else Explain how...
Make sure to write in complete sentences and realte it to children nothing else Explain how children reason in Kohlberg’s three levels of moral thought: preconventional moral thought, conventional moral thought, and postconventional moral thought. For each level, report a) what children emphasize as important as their basis for their moral beliefs and b) provide an example from the Heinz dilemma that reflects that type of moral reasoning. Each explanation (what children emphasize)
2.) Postfix to infix translator (NOTE: This is NOT the evaluator you have already coded!) •...
2.) Postfix to infix translator (NOTE: This is NOT the evaluator you have already coded!) • Create a java class called PostfixToInfixTranslator that includes a main method. • The code you write should prompt the user for an expression in postfix notation and use ArrayStack to output the equivalent expression in infix. • See the following session: Enter a postfix expression: 3 4 + 2 * In infix notation that is: ((3+4)*2) Translate another expression [y/n]? y Enter a postfix...
Please circle the answers and please make sure that it is true answer. Thank you. A...
Please circle the answers and please make sure that it is true answer. Thank you. A particle executes linear SHM with frequency 0.11 Hz about the point x = 0. At t = 0, it has displacement x = 0.33 cm and zero velocity. For the motion, determine the (a) displacement at t = 2.2 s, and (b) velocity at t = 2.2 s.
please answer all qustions and all parts and make sure you have the right answers. 1....
please answer all qustions and all parts and make sure you have the right answers. 1. An electric field is given by Ex = 3.5x3 kN/C. Find the potential difference between the points on the x axis at x = 1 m and x = 3 m. ..... kV --------------------------------- 2. (a) Find the maximum net charge that can be placed on a spherical conductor of radius 12 cm before dielectric breakdown of the air occurs. .... µC (b) What...
Create a portfolio using the four stocks and information below: ((((please please make sure the answers...
Create a portfolio using the four stocks and information below: ((((please please make sure the answers are correct please)))) Expected Return Standard Deviation Weight in Portfolio Stock A 21.00% 21.00% 15.00% Stock B 5.00% 17.00% 28.00% Stock C 7.00% 12.00% 11.00% Stock D 22.00% 22.00% 46.00% ---------------------- ---------------------- ---------------------- ---------------------- Correlation (A,B) 0.7000 ---------------------- ---------------------- Correlation (A,C) 0.4900 ---------------------- ---------------------- Correlation (A,D) 0.2500 ---------------------- ---------------------- Correlation (B,C) 0.4400 ---------------------- ---------------------- Correlation (B,D) 0.9600 ---------------------- ---------------------- Correlation (C,D) 0.2000 ---------------------- ----------------------...
Please label and write clearly. Please make sure to circle the answers Problem 2. We now...
Please label and write clearly. Please make sure to circle the answers Problem 2. We now wish to decide if there “use of e-cigarettes” and “income category” are dependent. To assist with this process, the table from before has been augmented with most of the expected frequencies (listed in parentheses): <$35,000 $35,000-$99,999 $100,000+ Total Vape 47 (34) 57 (58) 19 (31) 123 Do Not Vape 381 (394) 659 (???) 362 (???) 1402 Total 428 716 381 1525 a. Find the...
I need to make sure that my answers are correct please review. The Case as following:...
I need to make sure that my answers are correct please review. The Case as following: Focus Drilling Supplies has been growing steadily over the last 20 years. With increased exploration in the mining sector, the company has decided to expand their facilities for supplies and custom drill bit production to meet the increased demand. The expansion will occur over 4 years and is expected to require $2.8 million. Management has developed a payment plan for carrying out this expansion....
1) Consider the following infix expressions. What is the equivalent postfix (reverse Polish notation) expression? 16/(5+3)b)...
1) Consider the following infix expressions. What is the equivalent postfix (reverse Polish notation) expression? 16/(5+3)b) A*B+C*Dc) X × Y + W × Z + V × U 2) Consider the postfix (reverse Polish notation) 10 5 + 6 3 - /. What is the equivalent infix expression?
Make sure the answers are correct, well explained, thoughtful, and have no grammar mistakes. DO NOT...
Make sure the answers are correct, well explained, thoughtful, and have no grammar mistakes. DO NOT COPY answers from Chegg or other websites. The answer should be unique and original work. The answer should be no less than 300 words. Thanks in advance. Tell us the following: A time when you bought something based on each of the pricing strategies. - Clearance - Coupons - Bundling - Quantity Discount - Odd Pricing Also, what are something you are elastic AND...
Make sure the answers are correct, well explained, thoughtful, and have no grammar mistakes. DO NOT...
Make sure the answers are correct, well explained, thoughtful, and have no grammar mistakes. DO NOT COPY answers from Chegg or other websites. The answer should be unique and original work. The answer should be no less than 300 words. Thanks in advance. As an employee, doesn't have to be a retail employee for this DB mind you, what would motivate you most of the following and at least give me a sentence or two of WHY it is ranked...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT