1answer.
Ask question
Login Signup
Ask question
All categories
  • English
  • Mathematics
  • Social Studies
  • Business
  • History
  • Health
  • Geography
  • Biology
  • Physics
  • Chemistry
  • Computers and Technology
  • Arts
  • World Languages
  • Spanish
  • French
  • German
  • Advanced Placement (AP)
  • SAT
  • Medicine
  • Law
  • Engineering
LekaFEV [45]
3 years ago
13

You can combine the algorithms for converting between infix to postfix and for evaluating postfix to evaluate an infix expressio

n directly. To do so you need two stacks: one to contain operators and the other to contain operands. When an operand is encountered, it is pushed onto the operand stack. When an operator is encountered, it is processed as described in the infix-to-postfix algorithm*. When an operator is popped off the operator stack, it is processed as described in the postfix evaluation algorithm: The top two operands are popped off the operand stack, the operation is performed, and the result is pushed back onto the operand stack. Write a program to evaluate infix expressions directly using this combined algorithm.
Computers and Technology
1 answer:
marshall27 [118]3 years ago
4 0

Answer:

Check the explanation

Explanation:

import java.util.Stack;

/**

* Class to evaluate infix and postfix expressions.

*

public class InfixPostfixEvaluator {

/**

* Operators in reverse order of precedence.

*/

private static final String operators = "-+/*";

private static final String operands = "0123456789";

public int evalInfix(String infix) {

return evaluatePostfix(convert2Postfix(infix));

}

public String convert2Postfix(String infixExpr) {

char[] chars = infixExpr.toCharArray();

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

StringBuilder out = new StringBuilder(infixExpr.length());

for (char c : chars) {

if (isOperator(c)) {

while (!stack.isEmpty() && stack.peek() != '(') {

if (operatorGreaterOrEqual(stack.peek(), c)) {

out.append(stack.pop());

} else {

break;

}

}

stack.push(c);

} else if (c == '(') {

stack.push(c);

} else if (c == ')') {

while (!stack.isEmpty() && stack.peek() != '(') {

out.append(stack.pop());

}

if (!stack.isEmpty()) {

stack.pop();

}

} else if (isOperand(c)) {

out.append(c);

}

}

while (!stack.empty()) {

out.append(stack.pop());

}

return out.toString();

}

public int evaluatePostfix(String postfixExpr) {

char[] chars = postfixExpr.toCharArray();

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

for (char c : chars) {

if (isOperand(c)) {

stack.push(c - '0'); // convert char to int val

} else if (isOperator(c)) {

int op1 = stack.pop();

int op2 = stack.pop();

int result;

switch (c) {

case '*':

result = op1 * op2;

stack.push(result);

break;

case '/':

result = op2 / op1;

stack.push(result);

break;

case '+':

result = op1 + op2;

stack.push(result);

break;

case '-':

result = op2 - op1;

stack.push(result);

break;

}

}

}

return stack.pop();

}

private int getPrecedence(char operator) {

int ret = 0;

if (operator == '-' || operator == '+') {

ret = 1;

} else if (operator == '*' || operator == '/') {

ret = 2;

}

return ret;

}

private boolean operatorGreaterOrEqual(char op1, char op2) {

return getPrecedence(op1) >= getPrecedence(op2);

}

private boolean isOperator(char val) {

return operators.indexOf(val) >= 0;

}

private boolean isOperand(char val) {

return operands.indexOf(val) >= 0;

}

}

You might be interested in
Crees que es necesario que el estado Peruano, proponga nuevamente el aislamiento desde este 22 de diciembre al 02 de enero del 2
Nady [450]

Answer:

Efectivamente, es necesario que el gobierno de Perú establezca un nuevo aislamiento lo antes posible. Este período de fiestas, que va desde fines de diciembre hasta principios de enero, es un período de reuniones familiares y sociales, con lo cual dado el marco de una segunda oleada de coronavirus y la aparición de una nueva cepa de esta enfermedad en Gran Bretaña, es necesario extremar las precauciones y cuidados para que la situación no vuelva a complicarse como sucedió en el invierno pasado. Por lo tanto, es una necesidad tomar ciertas medidas restrictivas para evitar que la situación pase a mayores.

8 0
3 years ago
The presentation layer describes the layer where computers interact with _____
Dovator [93]
I believe its other computers 
5 0
3 years ago
Read 2 more answers
Based on the screenshot below which letter do you select to sort the items in an alphabetical order?
gladu [14]

Answer:

the smallest number start with the first number of the alphabet

6 0
3 years ago
Load the titanic sample dataset from the Seaborn library into Python using a Pandas dataframe, and visualize the dataset. Create
UNO [17]

Answer:

Following is given the data as required.

The images for histograms for age and gender are also attached below.

I hope it will help you!

Explanation:

8 0
3 years ago
Does -8 = -21?<br>[this is NOT a trick question]<br>Yes....?<br>No!​
Rudiy27

Answer:

No.

Explanation:

From my knowledge, negative 8 is 8 units to the left of zero, while 21 is 21 units to the left.

This means that they are two different negative numbers! If you see an equation like this, it would be labeled as false.

I'm quite sure I am correct, tell me so if otherwise! :)

#SpreadTheLove

8 0
3 years ago
Read 2 more answers
Other questions:
  • What natural boundary separated british territory from louisiana?
    7·1 answer
  • For this lab, you will work on a simple GUI application. The starting point for your work consists of four files (TextCollage, D
    5·1 answer
  • Assume there is a variable , h already associated with a positive integer value. Write the code necessary to count the number of
    13·1 answer
  • What is it called when two different files generate the same hashing result?
    15·1 answer
  • ___________________ are aggregated collections of memory and cpu resources that can be shared among groups of virtual machines o
    11·1 answer
  • 8. A sprite is a simple spider shaped thing with n legs coming out from a center point. The angle
    10·1 answer
  • You are planning a storage solution for a new Windows server. The server will be used for file and print services and as a datab
    6·1 answer
  • PLS HEEELLLP ASAP, DONT JOKE
    9·2 answers
  • What was that show where lowe’s were based off eye colors and the main character had orange eyes that let her mind control peopl
    14·2 answers
  • Programming that relies on the use of objects and methods to control complexity and solve problems is known as what type of prog
    7·1 answer
Add answer
Login
Not registered? Fast signup
Signup
Login Signup
Ask question!