Advertisement
Vita_Harvey

InfixParser_E

Mar 11th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.43 KB | None | 0 0
  1. package csc143.data_structures;
  2.  
  3. import java.awt.*;
  4. import javax.swing.*;
  5. import java.awt.event.*;
  6. import java.lang.*;
  7.  
  8. /**
  9.  * @author Vita Wiebe
  10.  * @version PA9: Stack/Queue Use, Parser
  11.  * This program takes a mathematical expression, user-input in
  12.  * the standard, infix notation, and produces an equivalent
  13.  * expression written in postfix notation.
  14.  */
  15. public class InfixParser implements ParserInterface  {
  16.  
  17.    // Fields
  18.    
  19.    // String s, the input string from user.
  20.    // Pre-condition: non-empty.
  21.    private String s;
  22.    // A String to hold a temporary value.
  23.    private String temp;
  24.    
  25.    // Our data structures, for handling the input, reordering,
  26.    // and eventual output of the postfix form of input.
  27.    private UnboundedArrayQueue outputQ;
  28.    
  29.    // For comparison when parsing the input string.
  30.    public final String operators = "+-/*%";
  31.    public final String numbers = "0123456789";
  32.    
  33.    /**
  34.     * Our class constructor.
  35.     */
  36.    public InfixParser() {      
  37.    }
  38.    
  39.    /**
  40.     * This method parses the input string into individual tokens.
  41.     * <p>
  42.     * For the minimal version of the assignment, this means breaking  
  43.     * the input string into single-character tokens, discarding all
  44.     * white space.
  45.     * For the standard version of the assignment, this entails
  46.     * breaking the input string into contiguous "runs" of alphanumeric
  47.     * characters (identifiers and integers) and punctuation (operators).
  48.     * <p>
  49.     * Negative numbers are not handled by this tokenizer.
  50.     *
  51.     * @param input The input string.
  52.     * @return A queue object containing the individual tokens.
  53.     */
  54.    public UnboundedArrayQueue tokenizeInput(String input) throws
  55.       IllegalArgumentException, NullPointerException {
  56.      
  57.       // Take input string, split into separate tokens, put into UnboundedQueue
  58.       this.s = input;
  59.       String[] sChar = s.split("");
  60.       UnboundedArrayQueue inputQ = new UnboundedArrayQueue();
  61.      
  62.       // Iterate thru sChar, combine each token into one token if
  63.       // consecutive elements are numerals (done to allow for numbers
  64.       // outside of 0-9 range).
  65.       for(int i = 0; i < sChar.length; i++) {
  66.          String tempString = "";
  67.          if(numbers.contains(sChar[i])) {
  68.             while(i < sChar.length && numbers.contains(sChar[i])){
  69.                tempString += sChar[i];
  70.                ++i;  
  71.             }
  72.             --i;
  73.             inputQ.add(tempString);
  74.          }else if(operators.contains(sChar[i])) {
  75.             inputQ.add(sChar[i]);
  76.          }              
  77.       }
  78.       return inputQ;        
  79.    }  
  80.            
  81.    /**
  82.     * This method converts a stream of tokens representing a
  83.     * well-formed arithmetic expression from infix notation to
  84.     * postfix notation.
  85.     * <p>
  86.     * For the minimal and standard versions of the assignment,
  87.     * this algorithm does not have handle the left-to-right
  88.     * associativity of the additive and multiplicative operators.
  89.     * This is avoided by taking advantange of the associative
  90.     * property of addition and multiplication.
  91.     * The challenge version of the assignment includes the left-
  92.     * to-right associativity, and therefore can also support the
  93.     * subtraction and division operators.
  94.     * <p>
  95.     * This method does not have to detect malformed input streams.
  96.     *
  97.     * @param input The input stream of tokens, the expression in
  98.     * infix notation.
  99.     * @return The output stream of tokens, the expression in postfix
  100.     * notation.
  101.     */
  102.    public UnboundedQueue<String> convertInfixToPostfix(UnboundedQueue<String> input) {
  103.      
  104.       UnboundedArrayStack<String> processStack = new UnboundedArrayStack(input.size());
  105.       UnboundedArrayQueue<String> outputQ = new UnboundedArrayQueue(input.size());
  106.      
  107.       // If the input is empty, output should be empty.
  108.       if(!input.hasContents()){
  109.          return new UnboundedArrayQueue();
  110.       } else {      
  111.          // Overall, this section parses the input queue, then puts
  112.          // the reodered elements into the stack.
  113.          String ops = "";
  114.          try {
  115.             // Iterate over inputQ. Add numbers to processStack.    
  116.             while(input.hasContents()) {        
  117.                String token = input.remove();                                                                  
  118.                if (!operators.contains(token)) {
  119.                   outputQ.add(token);
  120.                } else if (token.equals('(')) {
  121.                   processStack.push(token);
  122.                // Suss out operators, compare their order of operations              
  123.                } else if (operators.contains(token)) {
  124.                   token.compareTo((String)processStack.peek());
  125.                   if(token.compareTo((String)processStack.peek()) == -1) {
  126.                      while(token.compareTo((String)processStack.peek()) == -1) {
  127.                         outputQ.add(processStack.pop());
  128.                      }
  129.                   // If operator is > or == to precedence:
  130.                   // put on the stack.
  131.                   } else {  
  132.                      processStack.push(token);
  133.                   }  
  134.                } else if (token.equals(')')) {
  135.                      do {
  136.                         // Temp variable to store value
  137.                         // so pop() needn't be called more than once.
  138.                         temp = (String)processStack.pop();
  139.                      }   while(!temp.equals('('));                        
  140.                            outputQ.add(temp);
  141.                      if(processStack.peek().equals('(')) {
  142.                         outputQ.add(processStack.pop());
  143.                      }                  
  144.                }
  145.             }                      
  146.          } catch(NullPointerException n) {
  147.             System.err.println(n.getMessage());
  148.          }        
  149.       }
  150.      
  151.       // Add operators from the processStack into the outputQ.
  152.       while(processStack.hasContents()){
  153.          outputQ.add(processStack.pop());        
  154.       }
  155.       return outputQ;    
  156.    }
  157.    
  158.    /**
  159.     * This method formats the output stream of tokens into a
  160.     * single string for output. The individual tokens in the
  161.     * output stream are separated by exactly one space between
  162.     * adjacent tokens. There is no opening or closing space in
  163.     * the output String.
  164.     *
  165.     * @param output The output stream of tokens.
  166.     * @return The formatted output string.
  167.     */
  168.    public String formatOutput(UnboundedQueue<String> output){
  169.       String tokenStream = "";
  170.       if(output == null) {
  171.          throw new NullPointerException("This left me feeling a little empty...");        
  172.       } else {
  173.          tokenStream = output.remove();
  174.          while(output.hasContents()) {
  175.             tokenStream += " " + output.remove();
  176.          }
  177.       }            
  178.       return tokenStream;
  179.    }
  180.    
  181.    // Main application method from which the program is run.
  182.    public static void main(String[] args) {
  183.       InfixParser zoop = new InfixParser();
  184.       UnboundedArrayQueue test = zoop.tokenizeInput("3 2 + 4 * 2");
  185.       System.out.println(test);
  186.       // The following two calls produce "null" to console output.
  187.       // I am still attempting to figure out why output is null.
  188.       System.out.println(zoop.convertInfixToPostfix(test));
  189.       //System.out.println(zoop.formatOutput(zoop.convertInfixToPostfix(test)));
  190.        
  191.    }
  192. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement