Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The below java program works, but how do I make it so it has 3 different classes

ID: 3702844 • Letter: T

Question

The below java program works, but how do I make it so it has 3 different classes? One for the GUI, one for the expression tree and one for the operator & operands? Can you seperate these into three different classes that run the same program?

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Stack;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;

public class GUI {

private JButton btnConstruct;

private JTextField tfPostfix;

private JTextField tfInfix;

private JFrame f;

// constructor

GUI() {

init();

}

// a method to initialize and create a frame

private void init() {

// create a frame

f = new JFrame("Three Address Generator");

f.setLayout(new GridLayout(3,1));

// create a panel that contains a label and

// input box for inputting the postfix notation

JPanel p1 = new JPanel(new GridLayout(1,2));

JLabel l1 = new JLabel("Enter Postfix Notation :");

tfPostfix = new JTextField();

p1.add(l1);

p1.add(tfPostfix);

// creat the buttons and text area

btnConstruct = new JButton("Construct Tree");

// create a panel that contains a label and

// output box for outputting the infix notation

JPanel p2 = new JPanel(new GridLayout(1,2));

JLabel l2 = new JLabel("Infix Expression :");

tfInfix = new JTextField();

p2.add(l2);

p2.add(tfInfix);

// adding action listener to the button

btnConstruct.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent e) {

// read the postfix notation

String postfixExp = tfPostfix.getText().replaceAll(" ", "");

if(postfixExp.isEmpty()) {

// display some error message

// do something

System.out.println("No Postfix Notation is given");

return;

}

ExpressionTree et = new ExpressionTree();

String infixExp = et.constructTree(postfixExp);

if(infixExp.contains("Invalid")) {

JOptionPane.showMessageDialog(null, infixExp, "Error", JOptionPane.ERROR_MESSAGE);

} else {

tfInfix.setText(infixExp);

generateCode(infixExp);

}

}

});

// add components to the container

f.add(p1);

f.add(btnConstruct);

f.add(p2);

f.setSize(400, 200); // set the size of the frame

f.setLocationRelativeTo(null); // display frame in the middle of the screen

f.setResizable(false);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

}

private void generateCode(String infixExp) {

}

public static void main(String... aregs) {

GUI gui = new GUI();

}

}

class ExpressionTree {

PrintWriter p;

Stack<Node> stack = new Stack();

Stack<String> cstack = new Stack();

int operand = 0;

ExpressionTree() {

try {

this.p = new PrintWriter(new BufferedWriter(new FileWriter("_3AddressCode.txt")));

} catch (IOException ex) {

Logger.getLogger(ExpressionTree.class.getName()).log(Level.SEVERE, null, ex);

}

}

class Node {

char value;

Node left, right;

Node(char item) {

value = item;

left = right = null;

}

}

/**

   * Method to check whether c is an operator or not

   * @param c

   * @return

   */

boolean isOperator(char c) {

return c == '+' || c == '-'

|| c == '*' || c == '/'

|| c == '^';

}

/**

   * Method to check whether c is an operand or not

   * @param c

   * @return

   */

private boolean isOperand(char c) {

return c >= 48 && c <= 57;

}

/**

   * This method will take the root of a tree(The Expression tree we constructed)

   * and returns the array representing the inorder notation of that tree

   * by doing the inorder traversal

   * @param t

   */

String inorder(Node root) {

if (root != null) {

StringBuilder b = new StringBuilder();

b.append('('); // opening paranth of the expression

b.append(inorder(root.left)); // get the inorder notation of its left child

b.append(root.value);

b.append(inorder(root.right)); // get the inorder notaion of its right child

b.append(')'); // closing paranth of the expression

if(b.length() == 3) { // if there is only one value, i.e, only one operand

return root.value+"";

} else

return b.toString();

} else {

return "";

}

}

/**

   * This method, Given a postfix notation,

   * returns an Expression tree

   * @param postfix

   * @return

   */

String constructTree(String postfixExpression) {

Node root, right, left;

// tokenize the given postfix expression

char postfix[] = postfixExpression.toCharArray();

// for each token in the postfix expression

for (int i = 0; i < postfix.length; i++) {

// if the token is an operand

// then push it onto the stack

if (isOperand(postfix[i])) {

root = new Node(postfix[i]);

stack.push(root);

cstack.push(postfix[i]+"");

} else if(isOperator(postfix[i])){ // if it is an operator, then pop the stack twice and make those elements as children of root

// create a node for the root

root = new Node(postfix[i]);

// pop the stack

right = stack.pop();

left = stack.pop();

// make them children of the root

root.right = right;

root.left = left;

generate3AddressCode(postfix[i]);

// Add present root to the stack

stack.push(root);

} else {

// error case

// do something here

System.out.println("Invalid Expression");

p.close();

return "Invalid Token : "+postfix[i];

}

}

// only element will be present in the stack

// and that will be the root of our expression tree

root = stack.pop();

p.close();

// return the inorder traversal of this root

// to generate the desired infix expression

return inorder(root);

}

/**

   * Generates the 3 address code

   * @param s

   */

private void generate3AddressCode(char s) {

StringBuilder code = new StringBuilder();

code.append(getOperation(s));

code.append(' ');

code.append("R").append(operand); // R0, R1, R2, R3 etc

String right = cstack.pop(); // get the

String left = cstack.pop();

code.append(' ');

code.append(left);

code.append(' ');

code.append(right);

cstack.push("R"+operand);

operand++; // no of symboles incrementing

System.out.println(code.toString());

p.println(code.toString()); // write to file

}

/**

   * Returns the Mnemonic for a given operation

   * @param s

   * @return

   */

private String getOperation(char s){

switch(s) {

case '+' : return "Add";

case '-' : return "Sub";

case '*' : return "Mul";

case '/' : return "Div";

default : return "";

}

}

}

Explanation / Answer

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Stack;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;

public class GUI {

   private JButton btnConstruct;

   private JTextField tfPostfix;

   private JTextField tfInfix;

   private JFrame f;

   // constructor

   GUI() {

       init();

   }

   // a method to initialize and create a frame

   private void init() {

       // create a frame

       f = new JFrame("Three Address Generator");

       f.setLayout(new GridLayout(3, 1));

       // create a panel that contains a label and

       // input box for inputting the postfix notation

       JPanel p1 = new JPanel(new GridLayout(1, 2));

       JLabel l1 = new JLabel("Enter Postfix Notation :");

       tfPostfix = new JTextField();

       p1.add(l1);

       p1.add(tfPostfix);

       // creat the buttons and text area

       btnConstruct = new JButton("Construct Tree");

       // create a panel that contains a label and

       // output box for outputting the infix notation

       JPanel p2 = new JPanel(new GridLayout(1, 2));

       JLabel l2 = new JLabel("Infix Expression :");

       tfInfix = new JTextField();

       p2.add(l2);

       p2.add(tfInfix);

       // adding action listener to the button

       btnConstruct.addActionListener(new ActionListener() {

           @Override

           public void actionPerformed(ActionEvent e) {

               // read the postfix notation

               String postfixExp = tfPostfix.getText().replaceAll(" ", "");

               if (postfixExp.isEmpty()) {

                   // display some error message

                   // do something

                   System.out.println("No Postfix Notation is given");

                   return;

               }

               ExpressionTree et = new ExpressionTree();

               String infixExp = et.constructTree(postfixExp);

               if (infixExp.contains("Invalid")) {

                   JOptionPane.showMessageDialog(null, infixExp, "Error", JOptionPane.ERROR_MESSAGE);

               } else {

                   tfInfix.setText(infixExp);

                   generateCode(infixExp);

               }

           }

       });

       // add components to the container

       f.add(p1);

       f.add(btnConstruct);

       f.add(p2);

       f.setSize(400, 200); // set the size of the frame

       f.setLocationRelativeTo(null); // display frame in the middle of the screen

       f.setResizable(false);

       f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       f.setVisible(true);

   }

   private void generateCode(String infixExp) {

   }

   public static void main(String... aregs) {

       GUI gui = new GUI();

   }

}

ExpressionTree.java

package expression;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;

class ExpressionTree {

   PrintWriter p;

   Stack<Node> stack = new Stack();

   Stack<String> cstack = new Stack();

   int operand = 0;

   ExpressionTree() {

       try {

           this.p = new PrintWriter(new BufferedWriter(new FileWriter("_3AddressCode.txt")));

       } catch (IOException ex) {

           Logger.getLogger(ExpressionTree.class.getName()).log(Level.SEVERE, null, ex);

       }

   }

   class Node {

       char value;

       Node left, right;

       Node(char item) {

           value = item;

           left = right = null;

       }

   }

   /**
   *
   * This method will take the root of a tree(The Expression tree we constructed)
   *
   * and returns the array representing the inorder notation of that tree
   *
   * by doing the inorder traversal
   *
   * @param t
   *
   */

   String inorder(Node root) {

       if (root != null) {

           StringBuilder b = new StringBuilder();

           b.append('('); // opening paranth of the expression

           b.append(inorder(root.left)); // get the inorder notation of its left child

           b.append(root.value);

           b.append(inorder(root.right)); // get the inorder notaion of its right child

           b.append(')'); // closing paranth of the expression

           if (b.length() == 3) { // if there is only one value, i.e, only one operand

               return root.value + "";

           } else

               return b.toString();

       } else {

           return "";

       }

   }

   /**
   *
   * This method, Given a postfix notation,
   *
   * returns an Expression tree
   *
   * @param postfix
   *
   * @return
   *
   */

   String constructTree(String postfixExpression) {

       Node root, right, left;

       // tokenize the given postfix expression

       char postfix[] = postfixExpression.toCharArray();

       // for each token in the postfix expression

       for (int i = 0; i < postfix.length; i++) {

           // if the token is an operand

           // then push it onto the stack

           Operation op = new Operation(postfix[i]);
           if (op.isOperand()) {

               root = new Node(postfix[i]);

               stack.push(root);

               cstack.push(postfix[i] + "");

           } else if (op.isOperator()) { // if it is an operator, then pop the stack twice and make those elements as
                                           // children of root

               // create a node for the root

               root = new Node(postfix[i]);

               // pop the stack

               right = stack.pop();

               left = stack.pop();

               // make them children of the root

               root.right = right;

               root.left = left;

               generate3AddressCode(postfix[i]);

               // Add present root to the stack

               stack.push(root);

           } else {

               // error case

               // do something here

               System.out.println("Invalid Expression");

               p.close();

               return "Invalid Token : " + postfix[i];

           }

       }

       // only element will be present in the stack

       // and that will be the root of our expression tree

       root = stack.pop();

       p.close();

       // return the inorder traversal of this root

       // to generate the desired infix expression

       return inorder(root);

   }

   /**
   *
   * Generates the 3 address code
   *
   * @param s
   *
   */

   private void generate3AddressCode(char s) {

       StringBuilder code = new StringBuilder();

       code.append(Operation.getOperation(s));

       code.append(' ');

       code.append("R").append(operand); // R0, R1, R2, R3 etc

       String right = cstack.pop(); // get the

       String left = cstack.pop();

       code.append(' ');

       code.append(left);

       code.append(' ');

       code.append(right);

       cstack.push("R" + operand);

       operand++; // no of symboles incrementing

       System.out.println(code.toString());

       p.println(code.toString()); // write to file

   }

}

Operation.java

package expression;

public class Operation {

   private char c;

   /**
   * @param c
   */
   public Operation(char c) {
       super();
       this.c = c;
   }

   public char getC() {
       return c;
   }

   public void setC(char c) {
       this.c = c;
   }

   /**
   *
   * Returns the Mnemonic for a given operation
   *
   * @param s
   *
   * @return
   *
   */

   public static String getOperation(char s) {

       switch (s) {

       case '+':
           return "Add";

       case '-':
           return "Sub";

       case '*':
           return "Mul";

       case '/':
           return "Div";

       default:
           return "";

       }

   }

   /**
   *
   * Method to check whether c is an operator or not
   *
   * @param c
   *
   * @return
   *
   */

   public boolean isOperator() {

       return c == '+' || c == '-'

               || c == '*' || c == '/'

               || c == '^';

   }

   /**
   *
   * Method to check whether c is an operand or not
   *
   * @param c
   *
   * @return
   *
   */

   public boolean isOperand() {

       return c >= 48 && c <= 57;

   }

}

Output

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote