У меня раньше была эта проблема, и я забыл, как обойти эту проблему при создании дерева выражений. Каждый раз, когда я go компилирую этот код, он возвращает эту ошибку. Я не совсем понимаю, почему это дает мне это, потому что я подумал, что в своем коде я определил ExpressionTree. Ниже приведен полный код этого довольно простого GUI класса. строка, в которой происходит ошибка, является строкой 60.
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.BufferedWriter;
import javax.swing.*;
public class ExpressionTreeGUI {
//create GUI componets variables
private JTextField tfPostfix;
private JTextField tfInfix;
private JButton constructBtn;
private JFrame frame;
//Create constructor
ExpressionTreeGUI() {
init();
}
//create method to initialize frame
private void init() {
frame = new JFrame("Three Address Generator");
frame.setLayout(new GridLayout(3, 1));
//create panel for labels and buttons
JPanel mainP = new JPanel(new GridLayout(1, 2));
JLabel postfixLabel = new JLabel("Enter Postfix Notation: ");
tfPostfix = new JTextField();
mainP.add(postfixLabel);
mainP.add(tfPostfix);
//create buttons and text fields
constructBtn = new JButton("Contruct Tree");
//create panel fro the output of the infix notation
JPanel infixP = new JPanel(new GridLayout(1, 2));
JLabel infixL = new JLabel("Infix Expression: ");
tfInfix = new JTextField();
infixP.add(infixL);
infixP.add(tfInfix);
//create the action listener for the button
constructBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//read postfit expression
String postfitEXP = tfPostfix.getText().replaceAll(" ", "");
//create error message
if(postfitEXP.isEmpty()) {
System.out.println("No Postfix Notation Entered.");
return;
}
ExpressionTree tree = new ExpressionTree();
String infixEXP = tree.constructTree(postfitEXP);
if(infixEXP.contains("Invalid")) {
JOptionPane.showMessageDialog(null, infixEXP, "Error", JOptionPane.ERROR_MESSAGE);
}
else{
tfInfix.setText(infixEXP);
generateCode(infixEXP);
}
}
});
//Add components to container
frame.add(mainP);
frame.add(constructBtn);
frame.add(infixP);
frame.setSize(450,250);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private void generateCode(String infixEXP) {
}
public static void main(String[] args) {
ExpressionTreeGUI expressionTreeGUI = new ExpressionTreeGUI();
}
}
Ниже приведены другие классы для этой программы.
public class ExpressionTree {
PrintWriter p;
Stack<Node> stack = new Stack();
Stack<String> cStack = new Stack();
ExpressionTree() {
try {
this.p = new PrintWriter(new BufferedWriter(new FileWriter("_3AddressCode.txt")));
}//End try
catch(IOException ex) {
Logger.getLogger(EXPTree.class.getName()).log(Level.SEVERE, null, ex);
}//End catch
}
}//End class
public class Node {
char value;
Node left, right;
Node(char item) {
value = item;
left = right = null;
}
//Create method for check for c is an operator
boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
//Create method to check c is and operand
private boolean isOperand(char c) {
return c >= 48 && c <= 57;
}
//Create ,ethod to return tree notation in order
String inorder(Node root) {
if (root != null) {
StringBuilder b = new StringBuilder();
//open parentheses of expression
b.append('(');
//get inorder notation left
b.append(inorder(root.left));
b.append(root.value);
//get inorder notation right
b.append(inorder(root.right));
//close parentheses of expression
b.append(')');
//if theres only one opperand
if (b.length() == 3) {
return root.value+"";
}
else
return b.toString();
}
else {
return "";
}
}
//Create method to return expression tree after given postfix notation
String constructTree(String postfixEXP) {
Node root, right, left;
//Tokenize postfix expression
char postfix[] = postfixEXP.toCharArray();
//for loop for each token in postfix expression
for (int i=0; i<postfix.length; i++) {
//push token onto stack if it is an operand
if (isOperand(postfix[i])) {
root = new Node(postfix[i]);
stack.push(root);
cStack.push(postfix[i]+"");
}
//if token is an operator pop stack twice to make elements children of root
else if {
//create node for root
root = new Node(postfix[i]);
//pop stack
right = stack.pop();
left = stack.pop();
//Make them children of root
root.right = right;
root.left = left;
generate3AddressCode(postfix[i]);
//add current root to stack
stack.push(root);
}
else {
//create error
System.out.println("Invalid Expression");
p.close();
return "Invalid Token: " + postfix[i];
}
}
//only element in stack becomes root for tree
root = stack.pop();
p.close();
//return to inorder traversal to generate infix expression
return inorder(root);
}
//generate 3 code address
private void generate3AddressCode(char s) {
StringBuilder 3Acode = new StringBuilder();
3Acode.append(getOperation(s));
3Acode.append(' ');
//R1, R2, R3....
3Acode.append("R").append(operand);
String right = cStack.pop();
String left = cStack.pop();
3Acode.append(' ');
3Acode.append(left);
3Acode.append(' ');
3Acode.append(right);
cStack.push("R" + operand);
//number of symbols incrementing
operand++;
System.out.println(3Acode.toString());
//write to file
p.println(3Acode.toString());
}
//return operand label for given operation
private String getOperation(char s) {
switch(s) {
case '+' : return "Add";
case '-' : return "Sub";
case '*' : return "Mul";
case '/' : return "Div";
default : return "";
}
}
}