In: Computer Science
(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 + " )";
}
}
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