Advertisement
Guest User

Stack Postfix Evaluator

a guest
Apr 6th, 2013
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.94 KB | None | 0 0
  1. public class Stack<T>
  2. {
  3.     private T [ ] spaces;
  4.     private int TOS;
  5.  
  6.     private int capacity;
  7.  
  8.  
  9.     public Stack ( )
  10.     {
  11.         capacity = 50;
  12.         spaces  = (T [ ]) new Object [capacity];
  13.         TOS = capacity;
  14.  
  15.     }
  16.  
  17.     public boolean overflow ()
  18.     {
  19.         return (TOS == 0);
  20.     }
  21.  
  22.     public boolean empty ()
  23.     {
  24.         return (TOS == capacity);
  25.     }
  26.  
  27.     public boolean push (T newMem)
  28.     {
  29.         boolean ok = true;
  30.         if (overflow ())
  31.         {
  32.             System.out.println ("stack overflow");
  33.             ok = false;
  34.         }
  35.         else
  36.         {
  37.             spaces[--TOS] = newMem;
  38.             System.out.println (newMem + " pushed");
  39.         }
  40.  
  41.         return ok;
  42.     }
  43.  
  44.     public T pop ()
  45.     {
  46.         T popped = null;
  47.         if (empty ())
  48.             System.out.println ("empty");
  49.          else
  50.              popped = spaces[TOS++];
  51.  
  52.         return popped;
  53.  
  54.     }
  55.  
  56.     public T peekTOS ( )
  57.     {
  58.         T atTOS = null;
  59.         if (!empty ())
  60.             atTOS = spaces [TOS];
  61.         return atTOS;
  62.  
  63.     }
  64.    
  65.  
  66.  
  67.  
  68. }
  69.  
  70. ======================================================================================================================
  71. public class InfixToPostfix
  72. {
  73.    
  74.     public static String convert (String inString)
  75.     {
  76.         Stack<String> oprStack = new Stack<String> ( );
  77.         String postString = "";
  78.         inString = inString.trim ( );
  79.         int len = inString.length ( );
  80.         int i = 0;
  81.         String oprString = "";
  82.         String oprAtTop = "";
  83.         char c;
  84.        
  85.         for ( ;i < len; i++)
  86.         {
  87.             //get one char from the infix string
  88.             c = inString.charAt (i);
  89.            
  90.             //skip spaces
  91.             if (c == ' ');
  92.            
  93.             //push ( to the operator stack and treat that as the lowest priority operator
  94.             else if (c == '(')
  95.             {
  96.                 //convert a single char to a string for push
  97.                 oprString = "" + c;
  98.                 oprStack.push (oprString);
  99.             }
  100.            
  101.             //write every operand directly to the postfix string
  102.             else if ((c >= '0') && (c <= '9'))
  103.                 postString = postString + c;
  104.            
  105.             //pop all the operators and write them to the postfix string till a matching (
  106.             else if (c == ')')
  107.             {
  108.                 while (!oprStack.empty ( ))
  109.                 {
  110.                     oprString = oprStack.pop ( );
  111.                     if (!oprString.equals ("("))
  112.                         postString = postString + oprString;
  113.                     else
  114.                         break;
  115.                 }
  116.             }
  117.            
  118.            
  119.             //pop from the operator stack all the operators which have a higher or same priority then the one from the infix string
  120.             //and write them to the postfix string
  121.             //lastly, push the operator from the ininfix string to the operator stack
  122.             else
  123.             {
  124.                 oprString = "" + c;
  125.                 while (!oprStack.empty( ))
  126.                 {
  127.                     oprAtTop = oprStack.peekTOS ( );
  128.                     if (priority (oprString) <= priority (oprAtTop))
  129.                     {
  130.                         oprAtTop = oprStack.pop ( );
  131.                         postString = postString + oprAtTop;
  132.                     }
  133.                     else
  134.                         break;
  135.                 }
  136.                 oprStack.push (oprString);
  137.             }
  138.                      
  139.         }
  140.        
  141.         //clear the operator stack and write every popped operaotr to the postfix string
  142.         while (!oprStack.empty ( ))
  143.         {
  144.             oprAtTop = oprStack.pop ( );
  145.             postString = postString + oprAtTop;
  146.         }
  147.          
  148.         // System.out.println ("postfix = " + postString);
  149.         return postString;
  150.     }
  151.    
  152.     private static int priority (String aString)
  153.     {
  154.         int value = -1;
  155.         if (aString.equals ("("))
  156.             value = 0;
  157.         if ((aString.equals ("+")) || (aString.equals ("-")))
  158.             value =  1;
  159.         if ((aString.equals ("/")) || (aString.equals ("*")))
  160.             value = 2;
  161.        
  162.         return value;
  163.     }
  164.            
  165.            
  166.    
  167. }
  168. ===================================================================================================================
  169.  
  170. public class PostfixSolver {
  171.    
  172.     String inString = "";
  173.     int n1, n2;
  174.     String opr;
  175.     int solvedN;
  176.     String outString = "";
  177.     Stack inStack = new Stack();
  178.    
  179.     public String solve(String inString) {
  180.        
  181.         int len = inString.length();
  182.         int n;
  183.        
  184.         for (int i = 0; i < len; i++) {
  185.             n = inString.charAt(i);
  186.            
  187.             if(n >= 0 || n <= 9) {
  188.                 inStack.push(n);
  189.             }
  190.            
  191.             if(Integer.toString(n) == "=" || Integer.toString(n) == "-" || Integer.toString(n) == "/" ||
  192.                     Integer.toString(n) == "*") {
  193.                
  194.                 opr = Character.toString(inString.charAt(i));
  195.                 n1 = (int)inStack.pop();
  196.                 n2 = (int)inStack.pop();
  197.  
  198.                 switch (opr) {
  199.                 case "*": solvedN = n1*n2;
  200.                     break;
  201.                 case "/": solvedN = n1/n2;
  202.                     break;
  203.                 case "+": solvedN = n1+n2;
  204.                     break;
  205.                 case "-": solvedN = n1-n2;
  206.                     break; 
  207.                 }
  208.                
  209.                 inStack.push(solvedN);
  210.             }
  211.        
  212.         }
  213.        
  214.         return Integer.toString((int)inStack.pop());
  215.  
  216.     }
  217. }
  218. ===================================================================================================================
  219. import javax.swing.*;
  220.  
  221. import java.awt.*;
  222. import java.awt.event.*;
  223.  
  224.  
  225. public class Calculator extends JFrame implements ActionListener
  226. {
  227.     private JButton[] buttons;
  228.     private JTextField display;
  229.     private JPanel buttonPanel;
  230.     private Container contentPane;
  231.     InfixToPostfix converter = new InfixToPostfix();
  232.     PostfixSolver solve = new PostfixSolver();
  233.  
  234.     public static void main (String[] args)
  235.     {
  236.         Calculator myCalculator = new Calculator ( );
  237.         myCalculator.setVisible (true);
  238.  
  239.     }
  240.  
  241.     public Calculator ( )
  242.     {
  243.         setSize (300,600);
  244.         setTitle ("simple calculator");
  245.  
  246.         contentPane = getContentPane ( );
  247.         contentPane.setLayout (new BorderLayout ( ));
  248.  
  249.         display = new JTextField (30);
  250.         contentPane.add (display,BorderLayout.NORTH);
  251.  
  252.  
  253.         buttonPanel = new JPanel ( );
  254.         contentPane.add (buttonPanel, BorderLayout.CENTER);
  255.  
  256.         buttonPanel.setLayout (new GridLayout (4,4));
  257.  
  258.         buttons = new JButton[18];
  259.  
  260.         for (int i = 0; i < 10; i++)
  261.         {
  262.             buttons[i] = new JButton((new Integer (i)).toString ( ));
  263.             buttons[i].addActionListener (this);
  264.             buttonPanel.add (buttons[i]);
  265.         }
  266.  
  267.  
  268.         buttons[10] = new JButton ("+");
  269.         buttons[10].addActionListener (this);
  270.         buttonPanel.add (buttons[10]);
  271.         buttons[11] = new JButton ("-");
  272.         buttons[11].addActionListener (this);
  273.         buttonPanel.add (buttons[11]);
  274.         buttons[12] = new JButton ("/");
  275.         buttons[12].addActionListener (this);
  276.         buttonPanel.add (buttons[12]);
  277.         buttons[13] = new JButton ("*");
  278.         buttons[13].addActionListener (this);
  279.         buttonPanel.add (buttons[13]);
  280.         buttons[14] = new JButton ("(");
  281.         buttons[14].addActionListener (this);
  282.         buttonPanel.add (buttons[14]);
  283.         buttons[15] = new JButton (")");
  284.         buttons[15].addActionListener (this);
  285.         buttonPanel.add (buttons[15]);
  286.         buttons[16] = new JButton ("=");
  287.         buttons[16].addActionListener(this);
  288.         buttonPanel.add(buttons[16]);
  289.         buttons[17] = new JButton ("C");
  290.         buttons[17].addActionListener(this);
  291.         buttonPanel.add(buttons[17]);
  292.         setDefaultCloseOperation (EXIT_ON_CLOSE);
  293.  
  294.     }
  295.  
  296.     public void actionPerformed (ActionEvent x)
  297.     {
  298.         String which = x.getActionCommand ( );
  299.  
  300.         if (which.equals ("C"))
  301.             display.setText ("");
  302.         else if (which.equals ("=")) {
  303.             String postFix = converter.convert(display.getText());
  304.             String solution = solve.solve(postFix);
  305.             display.setText(postFix + " = " + solution);
  306.         }
  307.         else
  308.             display.setText (display.getText() + which);
  309.     }
  310. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement