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

如何为EditText设置默认值?未输入英寸时默认以0计算总身高

为EditText设置默认值并处理空输入的解决方案

原代码直接调用Integer.parseInt()会在EditText为空时抛出NumberFormatException,必须先判断输入文本是否为空,为空则使用默认值0,具体实现如下:

1. 封装工具方法处理输入(推荐)

写一个通用方法,安全地将EditText文本转为整数,空输入时返回默认值0:

private int getIntFromEditText(EditText editText) {
    String inputText = editText.getText().toString().trim();
    return inputText.isEmpty() ? 0 : Integer.parseInt(inputText);
}

调用这个方法获取身高值:

int hft = getIntFromEditText(takehtft);
int hin = getIntFromEditText(takehtin);

2. 直接在代码中判断(无需封装)

如果不想额外写方法,也可以直接对每个EditText做判断:

// 处理英尺输入,为空则默认0
String hftStr = takehtft.getText().toString().trim();
int hft = hftStr.isEmpty() ? 0 : Integer.parseInt(hftStr);

// 处理英寸输入,为空则默认0
String hinStr = takehtin.getText().toString().trim();
int hin = hinStr.isEmpty() ? 0 : Integer.parseInt(hinStr);

3. 计算总身高(英尺)

因为1英尺等于12英寸,总身高的计算要注意用浮点数除法避免精度丢失:

double totalHeightInFeet = hft + (hin / 12.0);

额外提示

  • 可以给EditText设置android:hint="请输入英寸",提前给用户输入提示,减少空输入场景;
  • 如果需要限制输入为正整数,可给EditText添加输入过滤器,避免非数字输入引发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:50:23