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

AWT事件线程抛出NumberFormatException:空字符串转整数(已初始化字符串)

Mastermind游戏NumberFormatException问题修复

问题描述

开发的Mastermind游戏GUI可正常启动,但点击**Überprüfung(检查)**按钮时,控制台抛出NumberFormatException异常,提示输入字符串为空。

问题根源

在auslesenEingabeFeld方法中,直接调用Integer.parseInt()转换输入框内容,但如果用户未在输入框中填写任何内容,textEingabeFeld[zeile][i].getText()会返回空字符串,而Integer.parseInt()无法将空字符串转换为整数,从而触发异常。

// 原代码中的问题代码段
speicher = textEingabeFeld[zeile][i].getText();
zeileEingabeFeld[i] = Integer.parseInt(speicher); // 空字符串会触发异常

修复方案

1. 增加输入校验逻辑

在转换前检查输入是否为空,同时验证输入是否为有效整数,避免无效值进入转换步骤。

2. 添加用户提示

当输入无效时,通过弹窗提示用户补全正确的数字输入,避免程序崩溃的同时提升体验。

修改后的auslesenEingabeFeld方法

import javax.swing.JOptionPane; // 需要导入弹窗类

public int[] auslesenEingabeFeld(int zeile) {
    int[] zeileEingabeFeld = new int[4];
    for(int i = 0; i < 4; i++) {
        String speicher = textEingabeFeld[zeile][i].getText().trim(); // 去除输入首尾空格
        
        // 校验输入是否为空或非数字
        if (speicher.isEmpty() || !speicher.matches("\\d+")) {
            JOptionPane.showMessageDialog(this, 
                "请在第" + (zeile+1) + "行第" + (i+1) + "列输入有效的数字!", 
                "输入错误", 
                JOptionPane.WARNING_MESSAGE);
            throw new IllegalArgumentException("无效输入:" + speicher);
        }
        
        zeileEingabeFeld[i] = Integer.parseInt(speicher);
    }
    return zeileEingabeFeld;
}

额外优化建议

  • 限制输入框仅接受数字:给输入框添加过滤器,从源头避免非数字输入
    // 在创建输入框的循环中添加以下代码(需要导入javax.swing.text.PlainDocument和AttributeSet)
    textEingabeFeld[zeile][spalte].setDocument(new PlainDocument() {
        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            // 只允许输入数字
            if (str.matches("\\d*")) {
                super.insertString(offs, str, a);
            }
        }
    });
    
  • 按钮点击时捕获异常:避免因输入错误导致程序崩溃
    btnber.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                dieAblaufsteuerung.eingebenZahl(zeile);
                zeile++;
            } catch (IllegalArgumentException ex) {
                // 无需额外提示,校验逻辑中已弹出提示
            }
        }
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:27:15