Question

Complete the following java program in which infix expressions should be converted to postfix expressions /**...

Complete the following java program in which infix expressions should be converted to postfix expressions

/** * An algebraic expression class that has operations such as conversion from infix

* expression to postfix expression,

* and evaluation of a postfix expression

*/

public class Expression {

/** * The infix of this expression

*/

private String infix;

/** * Constructs an expression using an infix.

*/

public Expression(String infix){

this.infix = infix;

}

/** * Converts an infix expression into a postfix expression.

* Tokens of the postfix expression are stored in order in an

* array list. The array list is returned.

* @return An array list of tokens of the postfix expression */

public ArrayList infixToPostfix(){

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

ArrayList postFixString = new ArrayList();

}

public static void main(String[] args) {

//Test method infixToPostfix using the following infix expressions. A + B * C + D, (A + B) * (C + D), A * B + C * D, and A + B + C + D } }

// End of Expression

0 0
Add a comment Improve this question Transcribed image text
Answer #1

ANSWER :

Hello, below is the code for the class above.

I have added additional methods for utility, like calculating precedence of the operators and for printing the arraylist which contains the postfix expressions.

Code :

import java.util.ArrayList;
import java.util.Stack;

/** * An algebraic expression class that has operations such as conversion from infix
* expression to postfix expression,
* and evaluation of a postfix expression
*/
public class Expression {

/** * The infix of this expression
*/
private String infix;

/** * Constructs an expression using an infix.
*/
public Expression(String infix){
this.infix = infix;
}

/** * Converts an infix expression into a postfix expression.
* Tokens of the postfix expression are stored in order in an
* array list. The array list is returned.
* @return An array list of tokens of the postfix expression */
public ArrayList infixToPostfix(){

Stack<String> stack = new Stack<>();
ArrayList postFixString = new ArrayList();
for(int i = 0; i<infix.length();i++){
char ch = infix.charAt(i);

// If the character is an empty space, skip the iteration.
if(ch==' ')
continue;

// If the character is an operand, add it to arraylist.
if((ch>=65 && ch<=90)||(ch>=97 && ch<=122))
postFixString.add(ch);

// If the character is an '(', push it to the stack.
else if(ch == '(')
stack.push(ch+"");

//If the character is an ')', pop and output from the stack until an '(' is encountered.
else if(ch == ')')
{
while (!stack.isEmpty() && !stack.peek().equals("("))
postFixString.add(stack.pop());

if (!stack.isEmpty() && !stack.peek().equals("(")){
System.out.println("Invalid Expression");
System.exit(0);
} else
stack.pop();
}
// the character is an operator
else {
while (!stack.isEmpty() && precedence(ch)<=precedence(stack.peek().charAt(0))){
if(stack.peek() == "(" ){
System.out.println("Invalid Expression");
System.exit(0);
}
postFixString.add(stack.pop());
}
stack.push(ch+"");
}
}
//return the converted post fix expression after conversion.
return postFixString;
}

//Method to determine the precedence while calculating the precedence of operators
public int precedence(char ch){
switch(ch){
case '^': return 3;
case '/':
case '*': return 2;
case '+':
case '-': return 1;
}
return -1;
}

//Method to print the post fix expression
public static void printPostfix(ArrayList arrayList){
for(Object object : arrayList)
System.out.print(object.toString()+" ");
System.out.println();
}

public static void main(String[] args) {
Expression expression = new Expression("A + B * C + D");
printPostfix(expression.infixToPostfix());

expression = new Expression("(A + B) * (C + D)");
printPostfix(expression.infixToPostfix());

expression = new Expression("A * B + C * D");
printPostfix(expression.infixToPostfix());

expression = new Expression("A * B + C * D");
printPostfix(expression.infixToPostfix());
}
}
//End of expression

Sample Output :​​​​​​PLEASE LEAVE A THUMBS UP IF THIS ANSWER HELPS YOU.

​​​​​THANK YOU:)

Add a comment
Know the answer?
Add Answer to:
Complete the following java program in which infix expressions should be converted to postfix expressions /**...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a java program to convert and print an infix expression to postfix expression. You can...

    Write a java program to convert and print an infix expression to postfix expression. You can use Java stack methods. (Must read input from System.in) Your main method should be as follow: public static void main(String args[]) { intopost p = new intopost (); String iexp, pexp; //infix postfix expression             try{ Scanner inf = new Scanner (System.in);                     // Read input from KB/ File while(inf.hasNext()){ // read next infix expression                                 iexp = inf.next(); // Assume method name to convert infix...

  • I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ________...

    I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ____________________________________________________________________________________________ C++ Program: #include <iostream> #include <string> #include <stdio.h> #include <math.h> using namespace std; //Stack class class STACK { private: char *str; int N; public: //Constructor STACK(int maxN) { str = new char[maxN]; N = -1; } //Function that checks for empty int empty() { return (N == -1); } //Push...

  • JAVA, please You must write a robust program meaning that your program should not crash with...

    JAVA, please You must write a robust program meaning that your program should not crash with any given data. Data validation must be done any time that user enters an input. Write a program that 1. Gets an infix expression form the user and evaluate the expression using stack ADT a. Finds the postfix equivalent of the given infix expression b. Evaluate the created postfix expression. c. Note: your program should not crash when you enter an invalid expression such...

  • This project is designed to practice with OOP, stack data structure, its applications, and C++/Java programming...

    This project is designed to practice with OOP, stack data structure, its applications, and C++/Java programming language. You will write a program that reads an infix expression, converts it to a postfix expression, evaluates the postfix expression, and prints out the answer. You must define and implement your own Stack class and a Calculator class. Your Stack class supports standard basic stack operations and you can implement it with an array or a linked list. You should create a class...

  • In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an...

    In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers For Example: Infix expression (6 + 2) * 5 - 8 / 4 to a postfix expression is  62+5*84/- The program should read the expression into character array infix and use the stack functions implemented in this chapter to help create the postfix expression in character array postfix. The...

  • Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression...

    Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression. Right now, it works with single digits. I need to modify it so that it can evaluate expressions with also 2 digits, example: (60+82)%72. Additionally I need to display an error when the parenthesis don't match like (89+8(. I have muted some line that would print the postfix expression with a space like: 22 8 + when the input...

  • Write a java code to implement the infix to postfix algorithm as described below: Algorithm convertTo...

    Write a java code to implement the infix to postfix algorithm as described below: Algorithm convertTo Post fix ( infix) // Converts an infix expression to an equivalent postfix expression operatorStack = a new empty stack postfix = anew empty string while (infix has characters left to parse) nextCharacter =next nonblank character of infix switch (nextCharacter) { case variable: Append nextCharacter to postfix break case 'A' operatorStack.push (nextCharacter) break case '+ case '-' : case '*' : case '/' while...

  • Write a java program for the following: Your program reads an infix expression represented by a...

    Write a java program for the following: Your program reads an infix expression represented by a string S from the standard input (the keyboard). Then your program converts the infix expression into a postfix expression P using the algorithm. Next, your program evaluates the postfix expression P to produce a single result R. At last, your program displays the original infix expression S, the corresponding postfix expression P and the final result R on the standard output ( the screen...

  • This code in C converts infix to postfix and evaluates it. The problem is that it...

    This code in C converts infix to postfix and evaluates it. The problem is that it only evaluates one digit expressions. I need to fix it so that it can evaluate 2 digits expressions as well. #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> #define SIZE 100 char s[SIZE]; int top=-1; void infixToPostfix(char *infix, char *postfix); void postfixEvaluation(char *postfix); void push(char elem){ s[++top]=elem; } char pop(){ return(s[top--]); } int pr(char elem){ // Order of precedence switch (elem) { case '(':...

  • Help with c++ program. The following code takes an infix expression and converts it to postfix....

    Help with c++ program. The following code takes an infix expression and converts it to postfix. When I compile the code it returns "Segmentation fault". However I don't know what causes this. #include #include #include using namespace std; template class Stack { public: Stack();//creates the stack bool isempty(); // returns true if the stack is empty T gettop();//returns the front of the list void push(T entry);//add entry to the top of the stack void pop();//remove the top of the stack...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT