【问题标题】:NumberFormatException in EditTextEditText 中的 NumberFormatException
【发布时间】:2013-06-14 12:50:25
【问题描述】:

我有一个计算两个 EditText 的 TextView。只要 EditText 中有一个数字,它就可以工作,但是一旦删除所有数字,我就会收到此错误

java.lang.NumberFormatException: 无法将 '' 解析为整数

我明白为什么我会收到错误,但我不知道如何解决它。我已经在这个网站上搜索并搜索了答案,但它们似乎不适用于我的情况。我试图捕捉 NumberFormatException 但我做不到。有什么帮助吗?

items = (EditText)findViewById(R.id.items);
itemcost = (EditText)findViewById(R.id.itemcost);
inventoryvalue = (TextView)findViewById(R.id.inventoryvalue);


TextWatcher textWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
calculateResult();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
};

items.addTextChangedListener(textWatcher);
itemcost.addTextChangedListener(textWatcher);
}

private void calculateResult() throws NumberFormatException {

String s1 = items.getText().toString();
    String s2 = itemcost.getText().toString();
    int value1 = Integer.parseInt(s1);
    int value2 = Integer.parseInt(s2);
    int result = value1 * value2; {

// Calculates the result
result = value1 * value2;
// Displays the calculated result
inventoryvalue.setText(String.valueOf(result));             
}

【问题讨论】:

  • 我保证今天晚些时候会检查你们所有其他人的答案。我喜欢看看有多少不同的方式我可以做某事。我是一名幼儿园程序员,但我正在学习。感谢您的回答。

标签: android string textwatcher numberformatexception


【解决方案1】:

检查你的字符串是否只包含数字:

s1 = s1.trim();
if (s1.matches("[0-9]+") {
 value1 = Integer.parseInt(s1);
}

【讨论】:

  • 我是新手,不知道修剪是什么意思,但会被谷歌搜索...你的功夫很强大!谢谢。不得不放一个 ) 来完成第二行,但我非常高兴..再次感谢。
【解决方案2】:

在 calculateResult 方法中将所有内容放在 if 块中:

if(items.getText().tostreing().length>0 && itemcost.getText().toString().length>0){
//your current method definition
}

【讨论】:

    【解决方案3】:

    将您的 afterTextChanged 方法更改为:

    public void afterTextChanged(Editable s) {
      if (s.length > 0)
          calculateResult();
    }
    

    【讨论】:

      【解决方案4】:

      在 calculateResult() 你做 Integer.parseInt(s1);不检查字符串 s1 或 s2 是否为空?

      因此,您不能将空字符串转换为 Int。尝试检查 s1 或 s2 是否为空,然后再尝试将它们转换为整数并使用它们进行计算...

      您可以使用 : .equals(String s) 检查字符串是否与其他字符串相等。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-20
        • 2013-01-12
        • 1970-01-01
        • 2023-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多