Write a Java program that reads an infix expression and converts it into a postf
ID: 644281 • Letter: W
Question
Write a Java program that reads an infix expression and converts it into
a postfix expression by using a stack.
In an arithmetic expression, there are 2 components involved: An operator and operand(s). For
example, for the expression:
x + y
operand1: x
operand2: y
operator: +
For your convenience, please assume input (infix format) operands as single characters. Each
character to represent an operand could either be an alphabetic character that corresponds to a
variable, or a numeric character that directly involves in the calculation of the infix expression after
it is converted into postfix format. In other words, assume expressions in the form x + y
Explanation / Answer
import java.io.*;
class stack
{
char[]=new char [100];
int top=-1;
void push(char c)
{
try
{
a[++top]=c;
}
catch(StringIndexOutofBoundsException e)
{
System.out.println("Stack full, no room to push, size=100");
System.exit(0);
}
}
char pop()
{
return a[top--];
}
boolean isEmpty()
{
return(top==-1)?true:false;
}
char peek()
{
return a[top];
}
}
public class InfixToPostfix
{
static Stack opeators = new Stack();
public static void main(String argv[]) throws IOException
{
String infix;
//create an input stream object
BufferedReader keyboard= new BufferedReader(new InputStreamReader(System.in));
//get input from user
System.out.print(" Enter the algebric Expression in infix:");
infix=keyboard.readLine();
//output as a postfix
System.out.println("The expression in postfix is:"+toPostfix(infix))
}
private static string toPostfix(String infix)
//converts an infix expression to postfix
{
char symbol;
String postfix="";
for(int i=0;i<infix.length();++i)
//while there is input to be read
{
symbol=infix.charAt(i);
//if it's operand, add it to the string
if(Character.isLetter(symbol))
postfix=postfix+symbol;
else if (symbol==')')
//push everything back to (
{
while(operators.peek()!='(')
{
postfix=postfix+operators.pop();
}
operators.pop();
}
else
//print operators occuring before it that have greater precedence
{
while(!operators.isEmpty())
postfix=postfix+operators.pop();
operators.push(symbol);
}
}
while(!operators.isEmpty())
postfix=postfix+operators.pop();
return postfix;
}
static int prec(char x)
{
if(x=='+'||x=='-')
return 1;
if(x=='*'||x=='/'||x=='%')
return 2;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.