Description of a JAVA program: You are to write a program name InfixToPostfix.ja
ID: 3778103 • Letter: D
Question
Description of a JAVA program:
You are to write a program name InfixToPostfix.java that converts an infix expression entered by the user to a postfix expression. The expression may contain the following tokens:
(1) Integer constants (a series of decimal digits).
(2) x (representing a value to be supplied later).
(3) Binary operators (+, -, *, / and %).
(4) Parentheses
In
Spaces between tokens are allowed but not required. The program will convert the expression to postfix form and display the converted expression.
Sample Output:
Enter infix expression: (x + 1) * (x – 2) / 4
Converted expression: x 1 + x 2 - * 4 /
Enter infix expression: 1 2 +
Error in expression!! No operator between operands. Also last token must be an operand.
Enter infix expression: 10.4
Error in expression!! Cannot accept floating point numbers.
Enter infix expression: 1 ( + 2)
Error in expression!! No operator between operand, and left parentheses.
Enter infix expression: 5 – (x – 2))
Error in expression!! No matching left parentheses for a right parentheses.
Enter infix expression: 1 ** 2
Error in expression!! The * operator cannot be preceded by a * operator.
Explanation / Answer
import java.io.*;
class Stack{
char a[]=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 Main{
static Stack operators = new Stack();
public static void main(String argv[]) throws IOException{
String infix;
//create an input stream object
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
//get input from user
System.out.print(" Enter the algebraic expression in infix: ");
infix = inp.readLine();
//output as postfix
System.out.println("The expression in postfix is: " + toPostfix(infix));
}
private static String toPostfix(String infix){
char symbol;
String postfix = "";
for(int i=0;i<infix.length();++i){
symbol = infix.charAt(i);
if (Character.isLetter(symbol)){
postfix = postfix + symbol;
}else if (symbol=='('){
operators.push(symbol);
}else if (symbol==')'){
while (operators.peek() != '('){
postfix = postfix + operators.pop();
}
operators.pop();
}else{
while (!operators.isEmpty() && !(operators.peek()=='(') && prec(symbol) <= prec(operators.peek()))
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;
}
}