简体   繁体   English

中缀到后缀表达式解析(带有 Swing 实现的 JAVA)

[英]Infix To Postfix Expression Parsing (JAVA w/ Swing Implementation)

I was tasked to Create a JAVA Swing GUI Program implementation that will output the Infix to Postfix and Infix to Prefix Notation Conversion, as well as how the conversion takes place via The Expression Parsing of the Prefix Stack and Operator Stack one by one. I was tasked to Create a JAVA Swing GUI Program implementation that will output the Infix to Postfix and Infix to Prefix Notation Conversion, as well as how the conversion takes place via The Expression Parsing of the Prefix Stack and Operator Stack one by one. in this case I used a JTable to output the Expression Parsing along with the Scanned Infix Notation Operators and Operands.在这种情况下,我使用了 JTable 到 output 表达式解析以及扫描中缀符号运算符和操作数。

The Problem: I am having a hard time creating the logic in outputing the Prefix stack and the Operator stack in the JTable.问题:我很难在 JTable 中创建输出前缀堆栈和运算符堆栈的逻辑。 Seen in the Picture Below: Table 1.1如下图所示:表 1.1

This is the objective we were tasked to create: Table 1.2这是我们的任务创建的目标:表 1.2

Same goes to the Infix to Prefix Notation Conversion: Table 1.3中缀到前缀符号转换也是如此:表 1.3

Anyone have any Ideas other than what I Created in Table 1.1?除了我在表 1.1 中创建的内容之外,还有其他人有什么想法吗?

Infix to Postfix Code:后缀代码的中缀:

public static int precedence(char o){
    switch(o){
        case '+':
        case '-':
            return 1;
        case '*':
        case '/':
            return 2;
        case '^':
            return 3;
    }
    return -1;
}

public String infixToPostfix(String expression){
    String result = "";
    Stack<Character> stack = new Stack<>();
    for (int i = 0; i < expression.length(); i++){
        char o = expression.charAt(i);
        if(precedence(o) > 0){
            while(stack.isEmpty() == false && precedence(stack.peek()) >= precedence(o)){
                result += stack.pop();
            }
            stack.push(o);

        }else if(o==')'){
            char x = stack.pop();
            while(x!='('){
                result += x;
                x = stack.pop();
            }
            
        }else if(o=='('){
            result += o;
            
        }else{
            result += o;
        }
    }
    for (int i =0; i <= stack.size(); i++){
        result += stack.pop();
    }
    return result;
}

Enter JButton Code:输入 JButton 代码:

private void EnterButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                             
    
    // ENTER BUTTON FUNCTION

    String expression = InfixInput1.getText(); 
    if(expression.isEmpty()){
        DisplayInput1.setText("NOTHING TO CONVERT!");
    }else{
        System.out.println("POSTFIX CONVERSION : "+infixToPostfix(expression));
        DisplayInput1.setText(expression);
        PostfixOutput.setText(infixToPostfix(expression));
    }
    PostfixTable.getColumnModel().getColumn(0).setPreferredWidth(5);
    PostfixTable.getColumnModel().getColumn(1).setPreferredWidth(5);
    PostfixTable.getColumnModel().getColumn(2).setPreferredWidth(5);

    String header[] = {"Scanned Symbol","Postfix Stack", "Operator Stack"};
    PostfixTable.setAutoCreateColumnsFromModel(true);
    TableColumn column1 = PostfixTable.getTableHeader().getColumnModel().getColumn(0);
    column1.setHeaderValue(header[0]);

    TableColumn column2 = PostfixTable.getTableHeader().getColumnModel().getColumn(1);
    column2.setHeaderValue(header[1]);

    TableColumn column3 = PostfixTable.getTableHeader().getColumnModel().getColumn(2);
    column3.setHeaderValue(header[2]);
    
    for(int i = 0; i <= expression.length()-1; i++){
        char a = expression.charAt(i);
        DefaultTableModel model = (DefaultTableModel) PostfixTable.getModel();
        model.addRow(new Object[]{a});
    }
}                   

I went ahead and created a bare-bones basic Swing GUI to replicate your GUI.我继续创建了一个简单的基本 Swing GUI 来复制您的 GUI。

Here's what the GUI looks like.这是 GUI 的样子。

在此处输入图像描述

The code you need to work on is located in the infixToPostfix method of the ConversionListener class.您需要处理的代码位于ConversionListener class 的infixToPostfix方法中。 I don't understand your conversion code well enough to put the call to the insertRow method in all the correct places.我不太了解您的转换代码,无法在所有正确的位置insertRow方法。

Here's the complete runnable code.这是完整的可运行代码。 I made the additional classes inner classes so I could post the code as one block.我将附加类设为内部类,这样我就可以将代码作为一个块发布。

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class InfixToPostfixGUI implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new InfixToPostfixGUI());
    }
    
    private final InfixToPostfixModel model;
    
    private JTextField infixField, postfixField;
    
    public InfixToPostfixGUI() {
        this.model = new InfixToPostfixModel();
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Infix to postfix parsing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(createDisplayPanel(), BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    private JPanel createDisplayPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        
        panel.add(createInfixPanel(), BorderLayout.NORTH);
        panel.add(createTablePanel(), BorderLayout.CENTER);
        panel.add(createPostfixPanel(), BorderLayout.SOUTH);
        
        return panel;
    }
    
    private JPanel createInfixPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JLabel label = new JLabel("Infix Expression:");
        panel.add(label);
        
        infixField = new JTextField(30);
        panel.add(infixField);
        
        JButton button = new JButton("Enter");
        button.addActionListener(new ConversionListener(this, model));
        panel.add(button);
        
        return panel;
    }
    
    private JPanel createTablePanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JTable table = new JTable(model.getTableModel());
        JScrollPane scrollPane = new JScrollPane(table);
        panel.add(scrollPane);
        
        return panel;
    }
    
    private JPanel createPostfixPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JLabel label = new JLabel("Postfix Expression:");
        panel.add(label);
        
        postfixField = new JTextField(30);
        postfixField.setEditable(false);
        panel.add(postfixField);
        
        return panel;
    }
    
    public String getInfixExpression() {
        return infixField.getText().trim();
    }
    
    public void setPostfixExpression() {
        postfixField.setText(model.getPostfixExpression());
    }
    
    public class ConversionListener implements ActionListener {
        
        private final InfixToPostfixGUI view;
        
        private final InfixToPostfixModel model;

        public ConversionListener(InfixToPostfixGUI view, InfixToPostfixModel model) {
            this.view = view;
            this.model = model;
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            String infixExpression = view.getInfixExpression();
            model.setInfixExpression(infixExpression);
            model.setPostfixExpression(infixToPostfix(infixExpression));
            view.setPostfixExpression();
        }
        
        private String infixToPostfix(String expression) {
            removeAllRows(model.getTableModel());
            String result = "";
            Stack<Character> stack = new Stack<>();

            for (int i = 0; i < expression.length(); i++) {
                char o = expression.charAt(i);
                if (precedence(o) > 0) {
                    while (!stack.isEmpty() && precedence(stack.peek()) >= precedence(o)) {
                        String token = Character.toString(stack.pop());
                        insertRow(model.getTableModel(), token, "", "", "", "");
                        result += token;
                    }
                    stack.push(o);

                } else if (o == ')') {
                    char x = stack.pop();
                    while (x != '(') {
                        result += x;
                        x = stack.pop();
                    }

                } else if (o == '(') {
                    String token = Character.toString(o);
                    insertRow(model.getTableModel(), token, "", "", "", "");
                    result += token;

                } else {
                    String token = Character.toString(o);
                    insertRow(model.getTableModel(), token, "", "", "", "");
                    result += token;
                }
            }

            for (int i = 0; i <= stack.size(); i++) {
                String token = Character.toString(stack.pop());
                insertRow(model.getTableModel(), token, "", "", "", "");
                result += token;
            }

            return result;
        }
        
        private int precedence(char o) {
            switch (o) {
            case '+':
            case '-':
                return 1;
            case '*':
            case '/':
                return 2;
            case '^':
                return 3;
            default:
                return -1;
            }
        }
        
        private void removeAllRows(DefaultTableModel tableModel) {
            int size = tableModel.getRowCount();
            for (int index = 0; index < size; index++) {
                tableModel.removeRow(0);
            }
        }
        
        private void insertRow(DefaultTableModel tableModel, String token, 
                String action, String result, String stack, String notes) {
            Object[] object = new Object[5];
            object[0] = token;
            object[1] = action;
            object[2] = result;
            object[3] = stack;
            object[4] = notes;
            tableModel.addRow(object);
        }
        
    }
    
    public class InfixToPostfixModel {
        
        private final DefaultTableModel tableModel;
        
        private String infixExpression, postfixExpression;
        
        public InfixToPostfixModel() {
            tableModel = new DefaultTableModel();
            tableModel.addColumn("Token");
            tableModel.addColumn("Action");
            tableModel.addColumn("Result");
            tableModel.addColumn("Stack");
            tableModel.addColumn("Notes");
        }

        public DefaultTableModel getTableModel() {
            return tableModel;
        }

        public String getInfixExpression() {
            return infixExpression;
        }

        public void setInfixExpression(String infixExpression) {
            this.infixExpression = infixExpression;
        }

        public void setPostfixExpression(String postfixExpression) {
            this.postfixExpression = postfixExpression;
        }

        public String getPostfixExpression() {
            return postfixExpression;
        }
        
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM