Thursday, 22 May 2014

infix to postfix conversion in java

import java.util.Stack;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
public class infix_to_postFix extends JFrame {

JFrame f =new JFrame("Infix TO PostFix");
JPanel jp;
JTextField infix_exp,post_exp;
JButton evaluate;
public infix_to_postFix(){

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - f.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - f.getHeight()) / 2);
f.setLocation(x-200, y-150);
f.setSize(320,200);
f.setVisible(true);
f.setResizable(false);
//f.setLayout(null);
jp=new JPanel();
infix_exp=new JTextField();
infix_exp.setPreferredSize(new Dimension(300, 50));
post_exp=new JTextField();
post_exp.setPreferredSize(new Dimension(300, 50));
evaluate=new JButton("Convert");
evaluate.setPreferredSize(new Dimension(100, 50));

Font font = new Font("SansSerif", Font.BOLD, 20);
f.add(jp);
f.revalidate();
infix_exp.setFont(font);
post_exp.setFont(font);
jp.add(infix_exp);
jp.add(evaluate);
jp.add(post_exp);
evaluate.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String Str1 = infix_exp.getText();
String Str2=convert(Str1);


post_exp.setText(Str2);

}
});
jp.revalidate();
validate();
}
public static int priority(char op){
if(op=='^')
return 3;
if(op=='/'||op=='*')
return 2;
if(op=='+'||op=='-')
return 1;
return 0;
}
public static String convert(String Str1){
Stack <Character> my_stack =new  Stack <Character>();
Str1=Str1+')';
String Str2="";
my_stack.push('(');
for(int i=0;i<Str1.length();i++){
char ch=Str1.charAt(i);
if(ch=='('){
my_stack.push('(');
}else if(Character.isLetter(ch)==true){
Str2=Str2+ch;
}else if(ch==')'){
while(my_stack.peek()!='('){
Str2=Str2+my_stack.peek();
my_stack.pop();
}
my_stack.pop();
}else{
while(priority(ch)<=priority(my_stack.peek())){
Str2=Str2+my_stack.peek();
my_stack.pop();
}
my_stack.push(ch);
}

}
return Str2;
}

public static void main(String args[]){
new infix_to_postFix();
}
}