Code Snippets

  

Java Source Code



Infix to Postfix Converter-Calculator (GUI)

This is a postfix converter, it converts an infix expression to postfix and calculates the result of the generated postfix

Submitted By: krizjaz
Actions:
Rating:
Views: 923

Language: Java

Last Modified: September 28, 2010
Instructions: Enter an equation in the textfield. Press
'Enter' or just click the Convert button and the postfix will be displayed in the text area. Then press 'Spacebar' or just click the Calculate button to calculate the result of the equation. And finally, press 'Spacebar' again or just click the Clear button.

Snippet


  1. import javax.swing.*;
  2. import java.awt.event.*;
  3. import java.awt.*;
  4. import javax.script.*;
  5. import java.util.Stack;
  6. public class InfixPostfixConverterCalculator extends JFrame implements ActionListener, KeyListener{
  7.         JTextArea taskOutput = new JTextArea();
  8.         JTextField tfield = new JTextField(), result = new JTextField();
  9.         JButton convertButton = new JButton("Convert"), calculateButton = new JButton("Calculate"), clearButton = new JButton("Clear");
  10.         StringBuffer textArea;// for storing stack values for conversion into integer (for calculation)
  11.         String[] forStack;// for storing stack elements
  12.  
  13.         public static void main(String[] args){
  14.                 InfixPostfixConverterCalculator frame = new InfixPostfixConverterCalculator();
  15.                 frame.setVisible(true);
  16.         }
  17.         public InfixPostfixConverterCalculator() {
  18.                 //Create the demo's UI.
  19.                 Container contentPane = getContentPane();
  20.                 contentPane.setLayout(null);
  21.                 contentPane.setBackground(Color.white);
  22.  
  23.                 setSize(290, 200);
  24.                 setResizable(false);
  25.                 setLocation(150, 150);
  26.                 setTitle("Postfix Calculator");
  27.  
  28.  
  29.                 JLabel label1 = new JLabel("Enter infix:");
  30.                 label1.setBounds(5, 5, 100, 30);
  31.                 contentPane.add(label1);
  32.  
  33.                 tfield.setBounds(105, 5, 100, 30);
  34.                 tfield.addKeyListener(this);
  35.                 tfield.requestFocus();
  36.                 contentPane.add(tfield);
  37.  
  38.                 JLabel label2 = new JLabel("Postfix:");
  39.                 label2.setBounds(5, 40, 100, 30);
  40.                 contentPane.add(label2);
  41.  
  42.                 taskOutput.setBounds(105, 40, 100, 30);
  43.                 taskOutput.setEditable(false);
  44.                 taskOutput.setBorder(BorderFactory.createLineBorder(Color.gray));
  45.                 contentPane.add(taskOutput);
  46.  
  47.                 JLabel label3 = new JLabel("Result:");
  48.                 label3.setBounds(5, 80, 100, 30);
  49.                 contentPane.add(label3);
  50.  
  51.                 result.setBounds(105, 80, 100, 30);
  52.                 result.setEditable(false);
  53.                 contentPane.add(result);
  54.  
  55.                 convertButton.setBounds(5, 130, 80, 30);
  56.                 convertButton.addActionListener(this);
  57.                 contentPane.add(convertButton);
  58.  
  59.                 calculateButton.setBounds(90, 130, 100, 30);
  60.                 calculateButton.addActionListener(this);
  61.                 calculateButton.setEnabled(false);
  62.                 contentPane.add(calculateButton);
  63.  
  64.                 clearButton.setBounds(195, 130, 80, 30);
  65.                 clearButton.addActionListener(this);
  66.                 contentPane.add(clearButton);
  67.  
  68.                 setDefaultCloseOperation(EXIT_ON_CLOSE);
  69.     }
  70.  
  71.     public void actionPerformed(ActionEvent e){
  72.                 Stack slk = new Stack();
  73.                 String exp = "(" + tfield.getText() + ")", exp2 = "";
  74.                 if((JButton)e.getSource() == convertButton){
  75.                         if(tfield.getText().length() != 0){
  76.                                 if(validChecker(exp)){ //if infix is valid
  77.                                         textArea = new StringBuffer();
  78.                                         int max = 0, num = 0;
  79.                                         for(int i = 0; i < exp.length(); i++){ // getting infix's maximum variables and operators
  80.                                                 if(!Character.isWhitespace(exp.charAt(i)))
  81.                                                         exp2 += exp.charAt(i);
  82.                                                 if(operators(exp.charAt(i)))
  83.                                                         max++;
  84.                                                 else if(Character.isDigit(exp.charAt(i)))
  85.                                                         num++;
  86.                                                 if(!Character.isDigit(exp.charAt(i)) && num != 0){
  87.                                                         num = 0;
  88.                                                         max++;
  89.                                                 }
  90.                                         }
  91.                                         exp = exp2;
  92.                                         calculateButton.setEnabled(true);
  93.                                         convertButton.setEnabled(false);
  94.                                         calculateButton.requestFocus();
  95.                                         clearButton.setEnabled(false);
  96.                                         forStack = new String[max];
  97.                                         for(int i = 0; i < max; i++)
  98.                                                 forStack[i] = "";
  99.                                         int counter = 0;
  100.                                         num = 0;
  101.                                         for(int i = 0; i < exp.length(); i++){// storing infix's variables and operators in a string array
  102.                                                 if(!Character.isDigit(exp.charAt(i)) && num != 0){
  103.                                                         num = 0;
  104.                                                         counter++;
  105.                                                 }
  106.                                                 if(exp.charAt(i) == '(' || exp.charAt(i) == ')'){
  107.                                                         forStack[counter] = "" + exp.charAt(i);
  108.                                                         counter++;
  109.                                                 }else if(Character.isDigit(exp.charAt(i))){
  110.                                                         forStack[counter] += exp.charAt(i);
  111.                                                         num++;
  112.                                                 }else if(operators(exp.charAt(i))){
  113.                                                         forStack[counter] = "" + exp.charAt(i);
  114.                                                         counter++;
  115.                                                 }
  116.                                         }
  117.                                         int len = exp.length();
  118.                                         for(int i = 0; i < forStack.length; i++){// conversion
  119.                                                 if(forStack[i].equals("("))
  120.                                                         slk.push(new Character('('));
  121.                                                 else if(forStack[i].equals(")")){
  122.                                                         while(!slk.empty() && !slk.peek().equals('(')){
  123.                                                                 taskOutput.append("" + slk.peek());
  124.                                                                 slk.pop();
  125.                                                         }
  126.                                                         slk.pop();
  127.                                                 }else if(forStack[i].equals("+") || forStack[i].equals("-")){
  128.                                                         if((Character)slk.peek() != '(' && (Character)slk.peek() != ')' && operators((Character)slk.peek())){
  129.                                                                 taskOutput.append("" + slk.peek());
  130.                                                                 slk.pop();
  131.                                                                 if(!slk.peek().equals('(')){
  132.                                                                         taskOutput.append("" + slk.peek());
  133.                                                                         slk.pop();
  134.                                                                 }
  135.                                                                 slk.push(new Character(forStack[i].charAt(0)));
  136.                                                         }else
  137.                                                                 slk.push(new Character(forStack[i].charAt(0)));
  138.                                                 }else if(forStack[i].equals("*") || forStack[i].equals("/")){
  139.                                                         if(slk.peek().equals('*') || slk.peek().equals('/')){
  140.                                                                 taskOutput.append("" + slk.peek());
  141.                                                                 slk.pop();
  142.                                                                 if(slk.peek().equals('*') || slk.peek().equals('/')){
  143.                                                                         taskOutput.append("" + slk.peek());
  144.                                                                         slk.pop();
  145.                                                                 }
  146.                                                                 slk.push(new Character(forStack[i].charAt(0)));
  147.                                                         }else
  148.                                                                 slk.push(new Character(forStack[i].charAt(0)));
  149.                                                 }else if(i == (len-1)){
  150.                                                         while(!slk.isEmpty()){
  151.                                                                 taskOutput.append("" + slk.peek());
  152.                                                                 slk.pop();
  153.                                                         }
  154.                                                 }else{
  155.                                                         taskOutput.append("" + forStack[i]);
  156.                                                 }
  157.                                         }
  158.                                 }else
  159.                                         JOptionPane.showMessageDialog(null, "Invalid infix!", "Oops!", JOptionPane.WARNING_MESSAGE);
  160.                         }else
  161.                                 JOptionPane.showMessageDialog(null, "Please enter an infix!", "Error!", JOptionPane.ERROR_MESSAGE);
  162.                 }else if((JButton)e.getSource() == calculateButton){
  163.                         try{
  164.                                 exp = "" + new ScriptEngineManager().getEngineByExtension("js").eval(exp);
  165.                         }catch(Exception ex){}
  166.                         for(int i = 0; i < exp.length(); i++){
  167.                                 if(exp.charAt(i) == '.'){
  168.                                         exp = exp.substring(0, i);
  169.                                         break;
  170.                                 }
  171.                         }
  172.                         result.setText(exp);
  173.                         calculateButton.setEnabled(false);
  174.                         clearButton.setEnabled(true);
  175.                         clearButton.requestFocus();
  176.                 }else{
  177.                         convertButton.setEnabled(true);
  178.                         calculateButton.setEnabled(false);
  179.                         taskOutput.setText("");
  180.                         tfield.setText("");
  181.                         result.setText("");
  182.                         tfield.requestFocus();
  183.                 }
  184.  
  185.         }
  186.         public void keyReleased(KeyEvent e){}
  187.         public void keyPressed(KeyEvent e){
  188.                 if(e.getKeyCode() == 10)
  189.                         convertButton.doClick();
  190.         }
  191.         public void keyTyped(KeyEvent e){}
  192.         public boolean operators(char a){
  193.                 return a == '+' || a == '-' || a == '*' || a == '/' || a == '(' || a == ')' ? true : false;
  194.         }
  195.         public boolean validChecker(String str){
  196.                 String errorCheck = "";
  197.                 try{
  198.                         String str2 = "" + new ScriptEngineManager().getEngineByExtension("js").eval(str);
  199.                 }catch(Exception ex){
  200.                         errorCheck = ex.toString();
  201.                 }
  202.                 if(errorCheck.length() != 0)
  203.                         return false;
  204.                 else
  205.                         return true;
  206.         }
  207. }

Copy & Paste


Comments

There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.