第二次作业

发布时间 2023-11-15 17:58:20作者: 卿*

【实验目的】

1.掌握软件开发的基本流程

2.掌握常用的软件开发方式和工具

【实验内容】

1.设计一个包含登录界面的计算机软件,该软件可以实现加减乘除以及开方功能,同时可以保存用户的历史计算记录(保存数据最好使用数据库)

【实验环境】

eclipse、windows11

【实验步骤】

一、用java实现登录页面

1.创建一个显示登陆界面;

2.创建一个显示计算器界面;

3.实现计算器的加减乘除功能及保存用户历史计算记录。

二,流程图

用户登录的流程图

  

 计算器运算程序流程图

三,关键代码

 LoginFrame:用于显示登录界面

代码为:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;

    public LoginFrame() {
        setTitle("登录");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(3, 2));

        JLabel usernameLabel = new JLabel("用户名:");
        usernameField = new JTextField();
        JLabel passwordLabel = new JLabel("密码:");
        passwordField = new JPasswordField();

        loginButton = new JButton("登录");
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 验证用户名和密码,如果正确则打开计算器界面
                if (usernameField.getText().equals("admin") && new String(passwordField.getPassword()).equals("123456")) {
                    CalculatorFrame calculatorFrame = new CalculatorFrame();
                    calculatorFrame.setVisible(true);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(null, "用户名或密码错误,请重试!", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        panel.add(usernameLabel);
        panel.add(usernameField);
        panel.add(passwordLabel);CalculatorFrame:用于显示计算器界面。CalculatorFrame:用于显示计算器界面。
        panel.add(passwordField);
        panel.add(new JLabel());
        panel.add(loginButton);

        add(panel);
    }
}

 

CalculatorFrame:用于显示计算器界面。

代码为:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CalculatorFrame extends JFrame {
    private JTextField displayField;
    private Calculator calculator;
    private History history;

    public CalculatorFrame() {
        setTitle("计算器");
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        displayField = new JTextField();
        displayField.setEditable(false);
        panel.add(displayField, BorderLayout.NORTH);

        calculator = new Calculator();
        history = new History();

        JPanel buttonsPanel = new JPanel();
        buttonsPanel.setLayout(new GridLayout(4, 4));

        String[] buttons = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
        for (String buttonText : buttons) {
            JButton button = new JButton(buttonText);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String command = e.getActionCommand();
                    if (command.equals("=")) {
                        String result = calculator.calculate(displayField.getText());
                        displayField.setText(result);
                        history.addRecord(displayField.getText(), result);
                    } else {
                        displayField.setText(displayField.getText() + command);
                    }
                }
            });
            buttonsPanel.add(button);
        }

        panel.add(buttonsPanel, BorderLayout.CENTER);
        panel.add(new JScrollPane(history.getHistoryPanel()), BorderLayout.SOUTH);

        add(panel);
    }
}

 

Calculator:用于实现加减乘除功能。

代码为:public class Calculator {
    public String calculate(String expression) {
        // 实现加减乘除功能,返回计算结果
        // 这里仅作示例,实际应用中可以使用表达式解析库如exp4j等
        return String.valueOf(eval(expression));
    }

    private double eval(final String str) {
        return new Object() {
            int pos = -1, ch;

            void nextChar() {
                ch = (++pos < str.length()) ? str.charAt(pos) : -1;
            }

            boolean eat(int charToEat) {
                while (ch == ' ') nextChar();
                if (ch == charToEat) {
                    nextChar();
                    return true;
                }
                return false;
            }

            double parse() {
                nextChar();
                double x = parseExpression();
                if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char) ch);
                return x;
            }

            double parseExpression() {
                double x = parseTerm();
                for (; ; ) {
                    if (eat('+')) x += parseTerm();
                    else if (eat('-')) x -= parseTerm();
                    else return x;
                }
            }

            double parseTerm() {
                double x = parseFactor();
                for (; ; ) {
                    if (eat('*')) x *= parseFactor();
                    else if (eat('/')) x /= parseFactor();
                    else return x;
                }
            }

            double parseFactor() {
                if (eat('+')) return parseFactor();
                if (eat('-')) return -parseFactor();

                double x;
                int startPos = this.pos;
                if (eat('(')) {
                    x = parseExpression();
                    eat(')');
                } else if ((ch >= '0' && ch <= '9') || ch == '.') {
                    while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
                    x = Double.parseDouble(str.substring(startPos, this.pos));
                } else {
                    throw new RuntimeException("Unexpected: " + (char) ch);
                }

                return x;
            }
        }.parse();
    }
}

 

History:用于保存用户历史计算记录。

代码为:import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class History {
    private List<String> records;
    private JTable historyTable;
    private DefaultTableModel tableModel;

    public History() {
        records = new ArrayList<>();
        tableModel = new DefaultTableModel();
        tableModel.addColumn("输入");
        tableModel.addColumn("输出");
        historyTable = new JTable(tableModel);
    }

    public void addRecord(String input, String output) {
        records.add(input + " = " + output);
        tableModel.addRow(new Object[]{input, output});
    }

    public JTable getHistoryPanel() {
        return historyTable;
    }
}

主函数:

代码为:import javax.swing.*;

public class Main {

public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LoginFrame().setVisible(true);
            }
        });
    }
}

运行Main类,将会弹出登录界面。输入正确的用户名和密码后,将打开计算器界面,可以进行加减乘除操作并查看历史计算记录。