answersLogoWhite

0


Best Answer

The following class should convert prefix to infix expression. I hope the logic is pretty simple and easy to understand. For any queries contact me at keepintouchsk@gmail.com

// Author: Skay

// Date: Nov 7, 2010

import java.util.Stack;

import java.util.Enumeration;

public class PrefixToInfixConverter

{

public static Stack<String> infixStk = new Stack<String>();

public PrefixToInfixConverter() { }

public static boolean isOper(String tstr)

{

if( tstr.equals("+") tstr.equals("-") tstr.equals("*") tstr.equals("/") )

return true;

else

return false;

}

public static String convert(String prefixStr)

{

String infixStr=new String();

String tempString = new StringBuffer(prefixStr).reverse().toString();

for(int i=tempString.length()-1;i>=0;i--)

{

while(tempString.charAt(i)==' ')

i--;

infixStk.push(String.valueOf(tempString.charAt(i)));

}

String[] val = new String[50];

int i,j;

while(infixStk.size()>1)

{

i=0;

while(!isOper(val[i++]=infixStk.pop()));

val[i-3] = new String("(" + val[i-2] + val[i-1] + val[i-3] + ")" );

for(j=i-3;j>=0;j--)

infixStk.push(val[j]);

}

return infixStk.pop();

}

}

Input: /-ab*c+de Output: ((a-b)/(c*(d+e)))

User Avatar

Wiki User

12y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

13y ago

/**

* Provides a collection of methods to convert postfix expressions to infix.

* Since expressions can contain both numbers and mathematical operators, all

* expressions use String objects to represent each part of the expression. The

* methods in this class are made to accept postfix expressions in any of the

* following formats:

* 1) String - Example: "3 4 +"

* 2) String[] - Example: {"3", "4", "+"}

* 3) Iterator<String> - Like String[], but for expressions in Collection objects

* 4) Iterable<String> - See above

*

* All methods translate their data into an Iterator<String>, and defer to that

* method to perform the actual parsing/translation.

*

* All methods will then also have the same return type: a String containing the

* unambiguous infix conversion of the postfix expression.

*

* Since all expressions have the possibility of being incorrectly formatted,

* the ExpressionFormatException is thrown if this is detected during processing.

*

* To accomodate algebraic expressions, values are not restricted by the characters

* they can represent. Numbers, letters, and all other non-operator symbols are

* allowed. "a b +" is perfectly valid input.

*

* These methods are designed to convert between one notation and the other; they

* will not find a numerical solution to any expressions.

*/

public final class PostfixToInfix {

/**

* Actual conversion method. Takes the expression stored in postfix and returns

* an infix representation of it.

*/

public static final String postfixToInfix(final Iterator<String> postfix)

throws ExpressionFormatException {

// Stack to hold values

final Stack<String> tokenStack = new Stack<String>();

// Start processing tokens

while (postfix.hasNext()) {

final String currentToken = postfix.next();

// Evaluate the current token and push it onto the stack

tokenStack.push(evaluateToken(currentToken, tokenStack));

}

// There should be exactly one element on the stack. Anything else

// signifies an input error.

if (tokenStack.size() != 1) {

throw new ExpressionFormatException();

}

// Last element of the stack is our result

return tokenStack.pop();

}

/**

* If token is a value, return the token.

* If token is an operator, perform the operation and return the result.

*/

private static final String evaluateToken(final String token, final Stack<String> tokenStack)

throws ExpressionFormatException {

if (isOperator(token)) {

// We know each operator works on two numbers...

// Check for correct number of values on stack

if (tokenStack.size() < 2) {

throw new ExpressionFormatException();

}

// Grab values to evaluate from stack

final String value2 = tokenStack.pop();

final String value1 = tokenStack.pop();

// Return evaluated expression

return "(" + value1 + " " + token + " " + value2 + ")";

} else { // currentToken = number

// If token is a number, it goes right onto the stack

return token;

}

}

// Overloaded variations of postfixToInfix method. Each just converts an

// expression from one format to Iterator<String> and calls that method.

public static final String postfixToInfix(final Iterable<String> postfix)

throws ExpressionFormatException {

return postfixToInfix(postfix.iterator());

}

public static final String postfixToInfix(final String[] postfix)

throws ExpressionFormatException {

return postfixToInfix(new ArrayIterator(postfix));

}

public static final String postfixToInfix(final String postfix)

throws ExpressionFormatException {

return postfixToInfix(new StringIterator(postfix));

}

/**

* Returns true iff token is a mathematical operator.

*

* Note: This method is a little over-the-top. It checks for every possible

* variation on mathematical characters. In the case of multiplication,

* there are a lot of variations on asterisks, 'x's, and dot notations.

* Typically the only real reason for this is for completeness.

*/

private static final boolean isOperator(final String token) {

// We can stop negative numbers from being identified as

// operators with this check.

if (token.length() == 1) {

// Ugliness

switch (token.charAt(0)) {

// Addition

case '+':

// Division

case '/':

case '\u0338':case '\u2044':case '\u2215':case '\u00F7':

// Subtraction

case '-':case '\u2010':case '\u2011':case '\u2012':

case '\u2013':case '\u2014':case '\u2015':case '\u2212':

// Multiplication

case 'x':case 'X':case '*':

case '\u00B7':case '\u0387':case '\u05BC':case '\u2022':

case '\u2027':case '\u2219':case '\u22C5':case '\u30FB':

case '\uFF65':case '\u00D7':case '\u2573':case '\u2715':

case '\u066D':case '\u203B':case '\u2217':case '\u2722':

case '\u2723':case '\u2724':case '\u2725':case '\u2731':

case '\u2732':case '\u2733':case '\u273A':case '\u273B':

case '\u273C':case '\u273D':case '\u2743':case '\u2749':

case '\u274A':case '\u274B':case '\uFE61':case '\uFF0A':

return true;

}// switch

}// if

return false;

}

// Conversion classes - used by postfixToInfix overloads to convert various

// datatypes to Iterator<String> types.

private static final class ArrayIterator implements Iterator<String> {

private final String[] strs;

private int index;

private ArrayIterator(final String[] strs) {

this.strs = strs;

index = 0;

}

public final boolean hasNext() {

return (index < strs.length);

}

public final String next() {

return strs[index++];

}

public final void remove() {

}

}

private static final class StringIterator implements Iterator<String> {

private final StringTokenizer stringtokenizer;

private StringIterator(final String str) {

stringtokenizer = new StringTokenizer(str);

}

public final boolean hasNext() {

return stringtokenizer.hasMoreTokens();

}

public final String next() {

return stringtokenizer.nextToken();

}

public final void remove() {

}

}

// Special Exception

private static final class ExpressionFormatException

extends IllegalArgumentException {

private ExpressionFormatException() {

}

}

}// PostfixToInfix

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

System.out.print("Enter the Element you want to sort[THEN PRESS ENTER]:");

num=new Scanner(System.in).nextInt();

}

int num,i;

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

Creamed on corn.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Java program that convert infix notation to prefix notation?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

Who invented postfix and infix?

infix: old Egyptians/Assirs some thousands year before prefix: Jan &#321;ukasiewicz (Polish Notation) postfix: Burks, Warren, and Wright (Reverse Polish Notation)


Why do compilers convert infix expressions to postfix?

people almost exclusively use infix notation to write mathematical expressions, computer languages almost exclusively allow programmers to use infix notation. However, if a compiler allowed infix expressions into the binary code used in the compiled version of a program, the resulting code would be larger than needed and very inefficient. Because of this, compilers convert infix expressions into postfix notation expressions, which have a much simpler set of rules for expression evaluation. Postfix notation gets its name from the fact that operators in a postfix expression follow the operands that they specify an operation on. Here are some examples of equivalent infix and postfix expressions Infix Notation Postfix Notation 2 + 3 2 3 + 2 + 3 * 6 3 6 * 2 + (2 + 3) * 6 2 3 + 6 * A / (B * C) + D * E - A - C A B C * / D E * + A C * - Where as infix notation expressions need a long list or rules for evaluation, postfix expressions need very few.


How do infix notation and postfix notation differ?

It's simply a matter of where the operators are placed in relation to their operands: infix: X + Y prefix: + X Y postfix: X Y + All of the above are equivalent. Prefix notation is also known as Polish notation, hence postfix is also known as reverse Polish notation. Given the infix equation A * B + C / D, the order of evaluation is always parenthesis, orders, divide/multiply, add/subtract (PODMAS), thus we must multiply A by B first, then divide C by D, and finally add the two results together. If we wish to perform the addition first, then we must re-write the equation with parenthesis: A * (B + C) / D. With postfix and prefix notation, operator precedence becomes superfluous because we always evaluate these expressions in left-to-right order: Infix A * B + C / D becomes postfix A B * C D / + or prefix / * A + B C D Infix A * (B + C) / D becomes postfix A B C + * D / or prefix + * A B / C D When we eliminate operator precedence with postfix or prefix notation, we greatly simplify the algorithm required to evaluate complex expressions. For example, given the postfix expression A B C + * D /, we simply read the symbols one at a time, placing them on a stack, until we encounter an operator. We then pop the first two elements off the stack, perform the operation, and then pop the result back on the stack. We repeat this process until there are no more symbols left, at which point the stack holds just one value: the result. With prefix notation, we place the operators on the stack instead of the operands. When we read the first operand we simply store it in an accumulator. We continue pushing operators onto the stack until we encounter the second operand, at which point we can pop the first operator off the stack, perform the operation and update the accumulator. We repeat this process until there are no symbols left, at which point the accumulator holds the final result. Note that when presented with an infix expression, a machine has to convert the expression to the equivalent prefix or postfix expression before it can be evaluated. By eliminating this conversion process, computation by machine can be performed with much greater speed.


What is prefix expression?

Example: prefix: * 2 + 3 4 infix: 2 * (3+4) postfix: 2 3 4 + *


Example program of how to convert infix notation to postfix notation and prefix notation?

/**************************//**********cReDo**********//*****mchinmay@live.com***///C PROGRAM TO CONVERT GIVEN VALID INFIX EXPRESSION INTO POSTFIX EXPRESSION USING STACKS.#include#include#include#define MAX 20char stack[MAX];int top=-1;char pop();void push(char item);int prcd(char symbol){switch(symbol){case '+':case '-':return 2;break;case '*':case '/':return 4;break;case '^':case '$':return 6;break;case '(':case ')':case '#':return 1;break;}}int isoperator(char symbol){switch(symbol){case '+':case '-':case '*':case '/':case '^':case '$':case '(':case ')':return 1;break;default:return 0;}}void convertip(char infix[],char postfix[]){int i,symbol,j=0;stack[++top]='#';for(i=0;iprcd(stack[top]))push(symbol);else{while(prcd(symbol)

Related questions

Program to convert infix to prefix?

I dont have the idea about the program but I know that prefix means the first starting letters of a particular things. I really think so there is a progam to convert infix to prefix but i might have misunderstood your question can you make it little simpler please.


Which data structure is needed to convert infix notations to post fix notations?

stack is the basic data structure needed to convert infix notation to postfix


Convert infix to prefix to postfix?

(a + b) * c / ((x - y) * z)


Which data structure convert logical to physical address?

Linear data structure is used to convert the logical address to physical address .Stack is used in this and the various conversion such as postfix,prefix and infix notation are come in this


Who invented postfix and infix?

infix: old Egyptians/Assirs some thousands year before prefix: Jan &#321;ukasiewicz (Polish Notation) postfix: Burks, Warren, and Wright (Reverse Polish Notation)


Why do compilers convert infix expressions to postfix?

people almost exclusively use infix notation to write mathematical expressions, computer languages almost exclusively allow programmers to use infix notation. However, if a compiler allowed infix expressions into the binary code used in the compiled version of a program, the resulting code would be larger than needed and very inefficient. Because of this, compilers convert infix expressions into postfix notation expressions, which have a much simpler set of rules for expression evaluation. Postfix notation gets its name from the fact that operators in a postfix expression follow the operands that they specify an operation on. Here are some examples of equivalent infix and postfix expressions Infix Notation Postfix Notation 2 + 3 2 3 + 2 + 3 * 6 3 6 * 2 + (2 + 3) * 6 2 3 + 6 * A / (B * C) + D * E - A - C A B C * / D E * + A C * - Where as infix notation expressions need a long list or rules for evaluation, postfix expressions need very few.


What are the three kinds of affixes?

Prefix, suffix and infix


What are INFIXES?

Infixes are morphemes that are attached within a word to change its meaning or grammatical category. They are different from prefixes (attached at the beginning) and suffixes (attached at the end) because they are inserted into the middle of a word. Ancient languages like Latin and Greek often use infixes.


Prefix suffix and infix examples with meaning and word definition?

An example of a prefix in the English language is pre, meaning before. An example of a suffix would be ing, meaning a verbal action. An example of an infix would be ful, meaning full of.


How do infix notation and postfix notation differ?

It's simply a matter of where the operators are placed in relation to their operands: infix: X + Y prefix: + X Y postfix: X Y + All of the above are equivalent. Prefix notation is also known as Polish notation, hence postfix is also known as reverse Polish notation. Given the infix equation A * B + C / D, the order of evaluation is always parenthesis, orders, divide/multiply, add/subtract (PODMAS), thus we must multiply A by B first, then divide C by D, and finally add the two results together. If we wish to perform the addition first, then we must re-write the equation with parenthesis: A * (B + C) / D. With postfix and prefix notation, operator precedence becomes superfluous because we always evaluate these expressions in left-to-right order: Infix A * B + C / D becomes postfix A B * C D / + or prefix / * A + B C D Infix A * (B + C) / D becomes postfix A B C + * D / or prefix + * A B / C D When we eliminate operator precedence with postfix or prefix notation, we greatly simplify the algorithm required to evaluate complex expressions. For example, given the postfix expression A B C + * D /, we simply read the symbols one at a time, placing them on a stack, until we encounter an operator. We then pop the first two elements off the stack, perform the operation, and then pop the result back on the stack. We repeat this process until there are no more symbols left, at which point the stack holds just one value: the result. With prefix notation, we place the operators on the stack instead of the operands. When we read the first operand we simply store it in an accumulator. We continue pushing operators onto the stack until we encounter the second operand, at which point we can pop the first operator off the stack, perform the operation and update the accumulator. We repeat this process until there are no symbols left, at which point the accumulator holds the final result. Note that when presented with an infix expression, a machine has to convert the expression to the equivalent prefix or postfix expression before it can be evaluated. By eliminating this conversion process, computation by machine can be performed with much greater speed.


What is prefix expression?

Example: prefix: * 2 + 3 4 infix: 2 * (3+4) postfix: 2 3 4 + *


C plus plus program using a stacks converting a postfix-infix?

Yes