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

JavaFX TextField转换整数触发NumberFormatException问题求助

问题:TextField输入整数过滤时触发NumberFormatException错误

我用普通TextField输入整数,基于输入数字执行过滤操作,已经耗了超一小时还是没解决。执行时抛出错误:NumberFormatException: 输入字符串为""

我的过滤函数:

private void fillAllListsFiltered() {
    List<Trip> trips = tripHib.getAllTrips();
    trips.forEach(c -> { if(c.getTime() > gt(tripTextTime) && c.getLength() > gt(tripTextLength)) tripListView.getItems().add(c);});
}

用于从TextField解析整数的方法(试过直接在第一个函数里用Integer.parseInt(tripTextTime.getText()),但同样无效,后来加了trim处理也没用):

private static int gt(TextField textField) {
    System.out.println(textField.getText());
    String text = textField.getText().trim();
    return Integer.parseInt(text);
}

问题原因

报错的核心是TextField内容为空,即使trim之后还是空字符串,而Integer.parseInt无法解析空串,直接抛出异常。

解决方案

在解析整数前先校验输入内容,处理空值或非数字的情况,以下是两种可行的修改方式:

方式1:修改gt方法,添加输入校验

private static int gt(TextField textField) {
    String text = textField.getText().trim();
    // 检查是否为空或非纯数字
    if (text.isEmpty() || !text.matches("\\d+")) {
        // 这里可以返回默认值(比如0),或者根据需求弹出提示告知用户输入有效数字
        return 0;
    }
    return Integer.parseInt(text);
}

方式2:在过滤函数中提前处理输入

private void fillAllListsFiltered() {
    List<Trip> trips = tripHib.getAllTrips();
    
    // 先处理两个输入框的数值,避免空串解析报错
    int timeThreshold = 0;
    try {
        String timeText = tripTextTime.getText().trim();
        if (!timeText.isEmpty()) {
            timeThreshold = Integer.parseInt(timeText);
        }
    } catch (NumberFormatException e) {
        // 非数字输入时的处理,比如提示用户
        e.printStackTrace();
    }
    
    int lengthThreshold = 0;
    try {
        String lengthText = tripTextLength.getText().trim();
        if (!lengthText.isEmpty()) {
            lengthThreshold = Integer.parseInt(lengthText);
        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    
    trips.forEach(c -> { 
        if(c.getTime() > timeThreshold && c.getLength() > lengthThreshold) {
            tripListView.getItems().add(c);
        }
    });
}

补充说明

之前加trim没用是因为当TextField完全没有输入时,trim()后的结果还是空字符串,依然会触发NumberFormatException,必须显式判断空值情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:40:28