Question

In: Computer Science

(JAVA) I have posted the same question 2 days ago, but it still has not solved...

(JAVA)

I have posted the same question 2 days ago, but it still has not solved yet.

I have "cannot be resolved or is not a field" error on

node.right; & node.left; under BuildExpressTree.java

//Main.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;

public class Main extends JFrame{
   private GridLayout glm = new GridLayout(3, 1, 5, 20);
   private JPanel jp1 = new JPanel();
   private JPanel jp2 = new JPanel();
   private JPanel jp3 = new JPanel();
   private GridLayout gl1 = new GridLayout (1, 2);
   private JLabel jl1 = new JLabel("Enter Postfix Expression", JLabel.CENTER);
   private JTextField jtf1 = new JTextField();
   private GridLayout gl2 = new GridLayout(1, 3, 5, 9);
   private JButton jbEvaluate = new JButton("Construct Tree");
   private GridLayout gl3 = new GridLayout(1, 2);
   private JLabel jl2 = new JLabel("Infix Expression", JLabel.CENTER);
   private JTextField jtf2 = new JTextField();
   private String postfixExpression;
   private int result;
  
   public String userInput(){
       return (String)jtf1.getText();
   }
  
   public Main(){
       setTitle("Infix Expression Evaluator");
       setSize(500, 200);
       setLayout(glm);
       jp1.setLayout(gl1);
       jp1.add(jl1);
       jp1.add(jtf1);
       add(jp1);
       jp2.setLayout(gl2);
       jp2.add(new JLabel(""));
       jp2.add(jbEvaluate);
       jbEvaluate.addActionListener(new EnterActionListener());
       jp2.add(new JLabel(""));
       add(jp2);
       jp3.setLayout(gl3);
       jp3.add(jl2);
       jp3.add(jtf2);
       jtf2.setEditable(false);
       jtf2.setBackground(Color.PINK);
       add(jp3);
       setLocationRelativeTo(null);
       setResizable(true);
       setVisible(true);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }

   class EnterActionListener implements ActionListener{
       public void actionPerformed(ActionEvent ae){
           jtf2.setText("");
           String result = "";
          
           try{
               result = BuildExpressionTree.constructTree(userInput());
               jtf2.setText(result);
               }catch(NumberFormatException nfe){
                   JOptionPane.showMessageDialog(null, "Amount must be numeric value", "Deposit Error", JOptionPane.WARNING_MESSAGE);
           }catch(EmptyStackException ese){
               JOptionPane.showMessageDialog(null, "Provide Expression to Calculate", "No Expression", JOptionPane.WARNING_MESSAGE);
           }
       }
       }
  
   public static void main (String[] args){
       Main main = new Main();
   }
}

//BuildExpressionTree.java

import java.util.*;
import javax.swing.*;
import javax.xml.soap.Node;

public class BuildExpressionTree {
   private static Stack<Node> stack = new Stack<Node>();
   private static Node node;
  
   public static boolean isOperator(String token){
       if(token == "+" || token == "-" || token == "*" || token == "/"){
           return true;
       }
       JOptionPane.showMessageDialog(null, "Invalid token" + token, "Token Error", JOptionPane.WARNING_MESSAGE);
       return false;
   }
  
   public static boolean isInteger(String token){
       try{
           if(Integer.parseInt(token) == 0 ||
           Integer.parseInt(token) == 1 ||
           Integer.parseInt(token) == 2 ||
           Integer.parseInt(token) == 3 ||
           Integer.parseInt(token) == 4 ||
           Integer.parseInt(token) == 5 ||
           Integer.parseInt(token) == 6 ||
           Integer.parseInt(token) == 7 ||
           Integer.parseInt(token) == 8 ||
           Integer.parseInt(token) == 9){
           return true;
           }
       }catch(NumberFormatException nfe){
           JOptionPane.showMessageDialog(null, "Invalid token" + token, "Token Error", JOptionPane.WARNING_MESSAGE);
           return false;
       }
       return true;
   }
  
   public static String[] postfixExpression(String postfixExp){
       String expression = postfixExp;
       String[] expressionArray = expression.split("\\s+");
       String splitExpression = "";
      
       for(int i = 0; i < expressionArray.length; i++){
           splitExpression += expressionArray[i];
       }
       StringTokenizer tokenizedExpression = new StringTokenizer(splitExpression);
       splitExpression = "";
      
       while(tokenizedExpression.hasMoreTokens()){
           String nextToken = tokenizedExpression.nextToken();
           splitExpression += nextToken + " ";
       }String[] tokens = splitExpression.split("\\s+");
       return tokens;
   }
  
   public static String constructTree(String expression) throws RuntimeException{
       stack = new Stack<Node>();
       String result;
       String[] expressionRead = postfixExpression(expression);
       for(int i = 0; i < expressionRead.length; i++){
           String nextToken = expressionRead[i];
           if(isInteger(nextToken)){
               node = (Node) new OperandNode(nextToken);
               stack.push(node);
           }else if(isOperator(nextToken)){
               node = (Node) new OperatorNode(nextToken);
               Node y;
               Node x;
              
               y = (Node) stack.pop();
               x = (Node) stack.pop();
              
               node.right = y;
               node.left = x;

               stack.push(node);
           }else{
               throw new RuntimeException();
           }
       }
       result = stack.peek().toString();
       return result;
   }
}

//Node.java


public abstract class Node {
   protected String data;
   protected Node left;
   protected Node right;
  
   public void setData(String data){
       this.data = data;
   }
  
   public String getData(){
       return data;
   }
}

class OperandNode extends Node{
   public OperandNode(String operand){
       this.data = operand;
       this.left = null;
       this.right = null;
   }
   public String toString(){
       return data + "";
   }
}

class OperatorNode extends Node{
   public OperatorNode(String operator){
       this.data = operator;
       this.left = null;
       this.right = null;
   }
  
   public void setLeft(Node left){
       this.left = left;
   }
   public Node getLeft(){
       return left;
   }
   public void setRight(Node right){
       this.right = right;
   }
   public Node getRight(){
       return right;
   }
   public String toString(){
       return "( " + this.left + " " + data + this.right + " )";
   }
}

Solutions

Expert Solution


ExpressionTree.java

import java.io.PrintWriter;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;

public class ExpressionTree
{
       //Operator stack, which will contain the Nodes of the expression tree.
       private Stack<Node> operandStack = new Stack<Node>();
       private Node added;

      
        public static boolean isOperator(String token)
        {
           // determines if it is the addition operator "+"
           if( token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"))
           {
               return true;
           }
          
           return false;
        }
      
      
        public static boolean isInteger(String token)
        {
            try
            {
                Integer.parseInt(token);
              
                return true;
            } catch (NumberFormatException nfe)
            {
                return false;
            }  
        }
      
      
       public String[] postfixExpressionDilimeter(String postfixExpression)
       {
           String expression; // will hold the postfix expression being read in
                          
           expression = postfixExpression;
          
           // split the string expression using the spaces as the dilimeters.
           String[] splitExpressionArray = expression.split("\\s+");
          
           // Put each section of the splitExpressionArray back into a string, so it can then be tokenized using the operators ["+-*/"] to split the expression even further.
           String splitExpression = "";
          
           for(int i = 0; i< splitExpressionArray.length ; i ++)
           {
               splitExpression += splitExpressionArray[i] + " ";
           }
          
           //tokenize the string splitExpression, using the operators "+, -, *, /" as the delimiters.
           StringTokenizer tokenizedExpression = new StringTokenizer(splitExpression, "+-*/)(", true);
          
           //Add each tokenized element from the tokenizedExpression, back into a string
          
           splitExpression = "";
          
             while (tokenizedExpression.hasMoreTokens())
             {
               String nxtToken = tokenizedExpression.nextToken();
              
               splitExpression += nxtToken + " ";  
             }
           
             //store each individual token from the formatted string into an array
             String[] tokens = splitExpression.split("\\s+");

           return tokens;
       }
      
       public String constructTree(String expression) throws RuntimeException
       {          
           // Each time this method is called, make sure we start off with a new operand stack
           operandStack = new Stack<Node>();

           // Will hold the final result of the expression that is evaluated.
           String result;

           // Separate the contents of the postfix expression being read in, and store each element into an String[] array.
           String[] expressionReadIn = postfixExpressionDilimeter(expression);

          
               //iterate through the tokens in the expression to format it into infix form
               for(int i = 0 ; i < expressionReadIn.length; i++)
               {
               //get the next token
               String nxtToken = expressionReadIn[i];  

              
               //If it is an operand, then push it onto the operand stack.
               if(isInteger(nxtToken))
               {
                   added = new OperandNode(nxtToken);
                   operandStack.push(added);
               }   
                 //else if it is an operator
                 else if(isOperator(nxtToken))
                 {
                   added = new OperatorNode(nxtToken);
                  
                   //pop two operands
                  
                   Node y; // Will hold the first operand that is popped from the operandStack
                   Node x; // Will hold the second operand that is popped from the operandStack
                  
                   y = operandStack.pop();
                   x = operandStack.pop();
                  
                   added.right = y;
                   added.left = x;                  
      
                   //push the sub expression back onto the operand stack
                   operandStack.push(added);  

                 }
               // otherwise, if it's not an operator or operand, then it is an invalid token
                 else
                 {
                   JOptionPane.showMessageDialog(null, "Invalid token " + nxtToken);

                   throw new RuntimeException();
                 }
             }

           result = operandStack.peek().toString();
          
           //Generate the Three Address Code, using the constructed binary expression tree
           generateThreeAddressCode(operandStack.peek());
          
           return result;
       }
       public void generateThreeAddressCode(Node node)
        {
            Stack<Node> S = new Stack<Node>();
        
           PrintWriter outPut;
          
           int registerCounter = 0; // Will keep track of what register the current calculation of the expression will be held in, during the traversal.
           String threeAddress = ""; // will hold the correctly formatted three address code of the current calculation that is being performed in the traversal.

           try {
               // It will print out the three address code of the expression into a file named ThreeAddressCode.txt
               outPut = new PrintWriter("ThreeAddressCode.txt", "UTF-8");

                // Check for empty tree, and return nothing if so.
                if (node == null)
                {
                }
              
                // Otherwise, push the tree node that will be traversed into the stack
                S.push(node);
              
                Node prev = null; // It will keep track of the previous node in the expression tree, during the traversal.

              
                // While the stack is not empty, do a post order traversal of the tree to generate the three address code
                while (!S.isEmpty())
                {
                    Node current = S.peek(); // it will keep track of the current node that the post order traversal is on
      
                    //Go down the tree until a leaf node is reached, and if so process it and then pop the top of the stack stack. Otherwise keep moving down
                    if (prev == null || prev.left == current || prev.right == current)
                    {
                        if (current.left != null)
                        {
                            S.push(current.left);
                        }
                        else if (current.right != null)
                        {
                            S.push(current.right);
                        }
                        // if both the left and right child of the current node is null, then you have reached a leaf node.
                        else
                        {
                           // If the current node is a left child, then store its data into its parent nodes .left section.
                           if(prev.left == current )
                           {
                               prev.left = S.pop();                          
                           }
                           // If the current node is a right child, then store its data into its parent nodes .right section.
                           else if(prev.right == current )
                           {
                               prev.right = S.pop();                      
                           }               
                        }
                    }
                    //Else, if you cannot go down left any further, then go back up the tree from the left node
                    else if (current.left == prev)
                    {
                       //if the child is right, then push it onto the stack
                        if (current.right != null)
                        {
                            S.push(current.right);
                        }
                        //otherwise process parent and pop stack
                        else
                        {
                            S.pop();                  
                        }
                    }
                    else if (current.right == prev)
                    {
                        S.pop();
                        if(current.data.equals("+"))
                       {
                           if(registerCounter ==0)
                           {
                               threeAddress = "Add " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                              
                               // If the current node is not the root node, then the stack is still not empty
                               if(!S.isEmpty())
                               {
                                    if(S.peek().left == current && S.peek().left != null)
                                    {
                                       S.peek().left.data = "R" + registerCounter;
                                    }
                                    else if(S.peek().right == current && S.peek().right != null)
                                    {
                                       S.peek().right.data = "R" + registerCounter;
                                    }
                                }                          
                               registerCounter++;                                                              
                           }
                           else if(!S.isEmpty())
                           {
                           threeAddress = "Add " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                            if(S.peek().left == current )
                            {
                               S.peek().left.data = "R" + registerCounter;
                            }
                            else if(S.peek().right == current)
                            {
                               S.peek().right.data = "R" + registerCounter;
                            }  
                           registerCounter++;
                           }
                          
                           else
                           {
                               threeAddress = "Add " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                           }                          
                           outPut.println(threeAddress);
                       }
                       else if(current.data.equals("-"))
                       {
                           if(registerCounter ==0)
                           {
                               threeAddress = "Sub " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                              
                               if(!S.isEmpty())
                               {
                                    if(S.peek().left == current && S.peek().left != null)
                                    {
                                       S.peek().left.data = "R" + registerCounter;
                                    }
                                    else if(S.peek().right == current && S.peek().right != null)
                                    {
                                       S.peek().right.data = "R" + registerCounter;
                                    }
                               }
                               registerCounter++;                                                              
                           }
                           else if(!S.isEmpty())
                           {
                          
                           threeAddress = "Sub " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                          
                            if(S.peek().left == current )
                            {
                               S.peek().left.data = "R" + registerCounter;
                            }
                            else if(S.peek().right == current)
                            {
                               S.peek().right.data = "R" + registerCounter;
                            }  
                           registerCounter++;
                           }
                           else
                           {
                               threeAddress = "Sub " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                           }
                           outPut.println(threeAddress);
                       }
                        else if(current.data.equals("*"))
                       {
                           if(registerCounter ==0)
                           {
                               threeAddress = "Mul " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                              
                               if(!S.isEmpty())
                               {
                                    if(S.peek().left == current && S.peek().left != null)
                                    {
                                       S.peek().left.data = "R" + registerCounter;
                                    }
                                    else if(S.peek().right == current && S.peek().right != null)
                                    {
                                       S.peek().right.data = "R" + registerCounter;
                                    }
                               }
                               registerCounter++;                                                              
                           }
                           else if(!S.isEmpty())
                           {
                          
                           threeAddress = "Mul " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                          
                            if(S.peek().left == current )
                            {
                               S.peek().left.data = "R" + registerCounter;
                            }
                            else if(S.peek().right == current)
                            {
                               S.peek().right.data = "R" + registerCounter;
                            }  
                           registerCounter++;
                           }
                           else
                           {
                               threeAddress = "Mul " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                           }
                           outPut.println(threeAddress);
                       }
                        else if(current.data.equals("/"))
                       {
                           if(registerCounter ==0)
                           {
                               threeAddress = "Div " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                              
                               if(!S.isEmpty())
                               {
                                    if(S.peek().left == current && S.peek().left != null)
                                    {
                                       S.peek().left.data = "R" + registerCounter;
                                    }
                                    else if(S.peek().right == current && S.peek().right != null)
                                    {
                                       S.peek().right.data = "R" + registerCounter;
                                    }
                               }
                               registerCounter++;                                                              
                           }
                           else if(!S.isEmpty())
                           {
                          
                           threeAddress = "Div " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                          
                            if(S.peek().left == current )
                            {
                               S.peek().left.data = "R" + registerCounter;
                            }
                            else if(S.peek().right == current)
                            {
                               S.peek().right.data = "R" + registerCounter;
                            }  
                           registerCounter++;
                           }
                           else
                           {
                               threeAddress = "Div " + "R" + registerCounter + " " + current.left.data + " " + current.right.data;
                           }
                           outPut.println(threeAddress);
                       }
                    }
      
                    prev = current;
                }
                outPut.close();
           }
           catch (Exception e)
           {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }  
        }    
}


OperatorNodeNode.java


public class OperatorNode extends Node
{
    public OperatorNode(String operator)
    {
        this.data = operator;
        this.left = null;
        this.right = null;
    }
  
   public void setLeft(Node left)
    {
        this.left = left;
    }
  
    public void setRight(Node right)
    {
        this.right = right;
    }
  
    public Node getLeft()
    {
        return left;
    }
public Node getRight()
    {
        return right;
    }
   @Override
   public String toString()
   {
       return "( " + this.left + " " + data + " " + this.right + " )";
   }
}

OperandNode.java


public class OperandNode extends Node
{
  
    public OperandNode(String operand)
    {
        this.data = operand;
        this.left = null;
        this.right = null;
    }
     
    @Override
    public String toString()
    {
        return data + "";
    }
}

ExpressionTreeGUI.java


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

@SuppressWarnings("serial")
public class ExpressionTreeGUI extends JFrame implements ActionListener
{
  
   ExpressionTree tree = new ExpressionTree();

   public static void main(String[] args) throws IOException{
       new ExpressionTreeGUI();
   }

   public ExpressionTreeGUI() throws IOException
   {
        // Creates the label which will be used to show where the user can enter the postfix expression they want represented
        JLabel enterPostfixExpressionLabel = new JLabel("Enter Postfix Expression");
        JPanel topPanel = new JPanel();
final JTextField postfixExpressionTextField = new JTextField();
       postfixExpressionTextField.setPreferredSize(new Dimension(250, 25));      
        topPanel.add(enterPostfixExpressionLabel, BorderLayout.EAST);
        topPanel.add(postfixExpressionTextField, BorderLayout.EAST);
        JLabel infixExpressionLabel = new JLabel("Infix Expression");
        JPanel bottomPanel = new JPanel();
        final JTextField expressionResultTextField = new JTextField();
       expressionResultTextField.setPreferredSize(new Dimension(250, 25));
       expressionResultTextField.setEditable ( false ); // set textArea non-editable
        bottomPanel.add(infixExpressionLabel, BorderLayout.EAST);
        bottomPanel.add(expressionResultTextField, BorderLayout.EAST);
        JPanel buttonPane = new JPanel();
       JButton constructTreeButton = new JButton("Construct Tree");
       constructTreeButton.addActionListener(new ActionListener()
       {
           public void actionPerformed(ActionEvent ae)
           {
               expressionResultTextField.setText("");
               String postfixExpression = postfixExpressionTextField.getText();
               String result = "";
               try
               {
                   result = tree.constructTree(postfixExpression);
                   expressionResultTextField.setText(result);
               }
               catch (RuntimeException e)
               {
                  
                   e.printStackTrace();
               }  
           }
       });
      
       buttonPane.add(constructTreeButton, BorderLayout.EAST);
       JFrame displayFrame = new JFrame ();
        displayFrame.setTitle("Three Adddress Generator");
      
        displayFrame.add(topPanel, BorderLayout.NORTH);
        displayFrame.add(buttonPane, BorderLayout.CENTER);
        displayFrame.add(bottomPanel, BorderLayout.SOUTH);


        displayFrame.pack ();
        displayFrame.setLocationRelativeTo(null);
        displayFrame.setVisible(true);
   }

   @Override
   public void actionPerformed(ActionEvent e) {
   }

}


Note: i cant able to upload node and stack class due to limited character


Related Solutions

I posted this exact question a few days ago and some doofus said it wasn't clear....
I posted this exact question a few days ago and some doofus said it wasn't clear. I don't know how to make it any more clear. This is all the information the question gives. There are 5 parts, A-E. Please answer them all. Thank you. Consider the titration of a 20.0 −mL sample of 0.110 M HC2H3O2 with 0.125 M NaOH. Determine each quantity: Part A) The initial pH = ? Part B) The volume of added base required to...
I have solved most of question and the answers I have so far are correct, I...
I have solved most of question and the answers I have so far are correct, I just need help finding out the lower bound and upper bound (All answers were generated using 1,000 trials and native Excel functionality.) Galaxy Co. distributes wireless routers to Internet service providers. Galaxy procures each router for $75 from its supplier and sells each router for $125. Monthly demand for the router is a normal random variable with a mean of 100 units and a...
The whole question has been posted below, but I have answered some of them. I need...
The whole question has been posted below, but I have answered some of them. I need help with questions B, E, and F. I need the critical value in question B. I need the answers for the differences in question E. I need the answers for test statistics in F. Thank you. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- Answer the one-way ANOVA questions using the data below. Use α = 0.01. 1 2 3 4 53 49 47 42 48 34 44 44 39 36...
This question was answered a while ago, but I feel something is still missing for some...
This question was answered a while ago, but I feel something is still missing for some reason, so I will be adding it again for another opinion. Thank you! You are given the data which consists of SAT math scores and University GPA at time of graduation with a four-year degree for fifteen students. Perform a regression analysis on your collected data and submit a written report. The SAT_Math column (variable) is the independent (explanatory) variable. The SAT_Univ column (variable)...
I Have posted my Java code below. Fix the toString, add, and remove implementations so that...
I Have posted my Java code below. Fix the toString, add, and remove implementations so that the following test cases work. Note: I have removed all the unnecessary inherited List implementations. I have them to: throw new UnsupportedException(); For compilation, you could also add //TODO. Test (Main) List list = new SparseList<>(); list.add("0"); list.add("1"); list.add(4, "4"); will result in the following list of size 5: [0, 1, null, null, 4]. list.add(3, "Three"); will result in the following list of size...
This question has been posted before (a good while ago so it's not likely anyone will...
This question has been posted before (a good while ago so it's not likely anyone will respond to comments), but the answers are either wrong or don't actually explain how the answers are obtained. (The answers in the back of the book are 24 for 3 and 100 for 5.) Mathematicians at the University of Florida solved a 30-year-old math problem using the theory of partitions. (Explore, Fall 2000.) In math terminology, a partition is a representation of an integer...
I posted this question looking for a new paper not an answer that's already posted on...
I posted this question looking for a new paper not an answer that's already posted on chegg since if someone already turned in that paper it will show as a copied paper... the question is.. write a paper of 300-600 words presenting your analysis of the following topic- Discuss shortages and surpluses and how they re-direct resources
BEFORE YOU ANSWER THIS QUESTION, PLEASE READ: I HAVE ALREADY POSTED THIS QUESTION MULTIPLE TIMES, AND...
BEFORE YOU ANSWER THIS QUESTION, PLEASE READ: I HAVE ALREADY POSTED THIS QUESTION MULTIPLE TIMES, AND I NEED HELP WITH THE JOURNAL ENTRIES. PLEASE INCLUDE THEM IN THE ANSWER. THANK YOU Overhead Variances, Four-Variance Analysis, Journal Entries Laughlin, Inc., uses a standard costing system. The predetermined overhead rates are calculated using practical capacity. Practical capacity for a year is defined as 1,000,000 units requiring 200,000 standard direct labor hours. Budgeted overhead for the year is $750,000, of which $300,000 is...
There is a question that has been raised during the class and I still did not...
There is a question that has been raised during the class and I still did not get it what are the criteria that influence the aggregate capacity planning (can someone explain it to me in 500 words so I can fully understand it )
(I have posted this question three times without any answer! please answer it. I really need...
(I have posted this question three times without any answer! please answer it. I really need the answer) Using openERP open-source (Odoo 10) systems, you will have to build HR & Finance business processes into the system. You will have to build ( a University or any company of your choosing) HR business processes using one of the tool you found interesting. You will have to find out improvements of the process Add the business rules to the processes You...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT