第二次作业

[实验目的]

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

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

[实验内容]

1.设计一个包含登录界面的计算器软件,该软件可以实现第一次作业中的全部功能,同时可以保存用户的历史计算记录(保存数据最好使用数据库)。

[实验工具]

1.用eclipse写登录界面和计算器。

2.用Mysql存储数据。

3.用jdbc连接数据库。

4.用Visio绘制流程图。

[流程图]

1.登录流程图:

 

 2.计算器流程图

 

 [登录界面]

  [登录失败]

  [登录成功]

[计算测试]

 

 

[数据库信息]

 

[登录界面代码]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class Calculator1 {
 
    private JFrame frame;
    private JPanel panel;
    private JTextField displayField;
    private JButton[] buttons;
    private String[] buttonLabels = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-", "*", "/", ".", "=" };
    private String displayText = "";
 
    private Connection conn;
 
    public Calculator1() {
        frame = new JFrame("计算器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        panel = new JPanel(new GridLayout(6,1));
 
        JLabel titleLabel = new JLabel("Log on", SwingConstants.CENTER);
        titleLabel.setFont(new Font("Arial", Font.BOLD, 20));
        panel.add(titleLabel);
 
        JLabel usernameLabel = new JLabel("用户名:");
        panel.add(usernameLabel);
 
        JTextField usernameField = new JTextField();
        panel.add(usernameField);
 
        JLabel passwordLabel = new JLabel("密码:");
        panel.add(passwordLabel);
 
        JPasswordField passwordField = new JPasswordField();
        panel.add(passwordField);
 
        JButton loginButton = new JButton("登录");
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                String password = String.valueOf(passwordField.getPassword());
 
                if (login(username, password)) {
                    panel.setVisible(false);
                    initializeCalculator();
                } else {
                    JOptionPane.showMessageDialog(frame, "登录失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panel.add(loginButton);
 
        frame.add(panel);
 
        frame.setSize(500, 600);
        frame.setVisible(true);
    }

  

[Login方法验证用户登录信息]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private boolean login(String username, String password) {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost/calculator?useSSL=false", "root", "123456");
 
        String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setString(1, username);
        stmt.setString(2, password);
        ResultSet rs = stmt.executeQuery();
 
        if (rs.next()) {
            return true; // 登录成功
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    return false; // 登录失败
}

  

[计算器界面]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
private void initializeCalculator() {
    JPanel calcPanel = new JPanel(new GridLayout(9, 1));
 
    JLabel titleLabel = new JLabel("count", SwingConstants.CENTER);
    titleLabel.setFont(new Font("Arial", Font.BOLD, 20));
    calcPanel.add(titleLabel);
 
    displayField = new JTextField();
    displayField.setEditable(false);
    calcPanel.add(displayField);
 
    buttons = new JButton[buttonLabels.length];
    for (int i = 0; i < buttonLabels.length; i++) {
        buttons[i] = new JButton(buttonLabels[i]);
        buttons[i].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String buttonText = ((JButton) e.getSource()).getText();
 
                if (buttonText.equals("=")) {
                    calculate();
                } else {
                    displayText += buttonText;
                    displayField.setText(displayText);
                }
            }
        });
        calcPanel.add(buttons[i]);
    }
 
    frame.add(calcPanel);
 
    frame.setSize(500, 600);
    frame.revalidate();
}

  

[EvaluateExpression类来计算表达式的结果]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package 计算器;
 
import java.util.Stack;
 
public class EvaluateExpression {
    public static double evaluate(String expression) {
        char[] tokens = expression.toCharArray();
 
        Stack<Double> values = new Stack<Double>();
        Stack<Character> operators = new Stack<Character>();
 
        for (int i = 0; i < tokens.length; i++) {
            if (tokens[i] >= '0' && tokens[i] <= '9') {
                StringBuilder sb = new StringBuilder();
 
                while (i < tokens.length && ((tokens[i] >= '0' && tokens[i] <= '9') || tokens[i] == '.')) {
                    sb.append(tokens[i]);
                    i++;
                }
 
                values.push(Double.parseDouble(sb.toString()));
                i--;
            } else if (tokens[i] == '(') {
                operators.push(tokens[i]);
            } else if (tokens[i] == ')') {
                while (operators.peek() != '(') {
                    values.push(applyOperator(operators.pop(), values.pop(), values.pop()));
                }
                operators.pop();
            } else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/') {
                while (!operators.empty() && hasPrecedence(tokens[i], operators.peek())) {
                    values.push(applyOperator(operators.pop(), values.pop(), values.pop()));
                }
                operators.push(tokens[i]);
            }
        }
 
        while (!operators.empty()) {
            values.push(applyOperator(operators.pop(), values.pop(), values.pop()));
        }
 
        return values.pop();
    }
 
    private static boolean hasPrecedence(char op1, char op2) {
        if (op2 == '(' || op2 == ')') {
            return false;
        }
        if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
            return false;
        }
        return true;
    }
 
    private static double applyOperator(char operator, double b, double a) {
        switch (operator) {
            case '+':
                return a + b;
            case '-':
                return a - b;
            case '*':
                return a * b;
            case '/':
                if (b == 0) {
                    throw new ArithmeticException("除数不能为零");
                }
                return a / b;
        }
        return 0;
    }
}

 

[计算器调用]

1
2
3
4
5
6
7
8
9
private void calculate() {
    try {
        double result = EvaluateExpression.evaluate(displayText);
        displayField.setText(String.valueOf(result));
        displayText = "";
    } catch (Exception e) {
        JOptionPane.showMessageDialog(frame, "无效表达式", "错误", JOptionPane.ERROR_MESSAGE);
    }
}

 

[主函数调用]

1
2
3
4
5
6
7
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new Calculator1();
        }
    });
}

 

[Mysql数据库和表]

1
2
3
4
5
6
7
8
9
10
11
12
-- 创建名为"calculator"的数据库
CREATE DATABASE IF NOT EXISTS calculator;
 
-- 使用"calculator"数据库
USE calculator;
 
-- 创建名为"users"的表
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL
);

  

 

 

 

posted @   11༺零༻11  阅读(51)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示