You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

简易Java计算器点击等号按钮时触发Null Pointer Exception错误求助

解决Java计算器点击等号触发NullPointerException的问题

问题根源

  • 直接调用Double.parseDouble(buffer)时,buffer可能未初始化(默认值为null),这会直接抛出NullPointerException。
  • 未校验textField.getText()的内容是否为空或非数字格式,即使不会触发NPE,也会抛出NumberFormatException。
  • 虽然compute方法里判断了operator是否为null,但在调用compute之前,buffer为null的情况已经触发了NPE。

修复后的代码

public class Calc {

    private JFrame frame;
    String buffer, operator;
    JTextField textField = new JTextField();

    public Calc() {
        JButton btnEquals = new JButton("=");
        btnEquals.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 先校验核心变量和输入合法性
                if (buffer == null || operator == null || textField.getText().trim().isEmpty()) {
                    textField.setText("ERR");
                    return;
                }
                
                try {
                    double left = Double.parseDouble(buffer);
                    double right = Double.parseDouble(textField.getText().trim());
                    textField.setText(compute(operator, left, right));
                    operator = null;
                    buffer = null;
                } catch (NumberFormatException ex) {
                    // 处理非数字输入的异常
                    textField.setText("ERR");
                }
            }
       });
    }

    public static String compute(String operator, double left, double right) {
        switch (operator) {
            case "+":
                return Double.toString(left + right);
            // 可扩展添加其他运算符的处理逻辑
            default:
                return "ERR"; // 不支持的运算符
        }
    }
}

关键修复点

  • 在解析数字前,先判断buffer、operator是否为null,同时检查输入框内容是否为空。
  • 用try-catch包裹Double.parseDouble调用,处理用户输入非数字字符的异常情况。
  • 移除compute方法中多余的operator != null判断,因为前面已经完成了前置校验。

内容的提问来源于stack exchange,提问作者user22190533

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:37:10