繁体   English   中英

EditText中的NumberFormatException

[英]NumberFormatException in EditText

我有一个TextView计算两个EditText。 只要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));             
}

检查您的字符串是否仅包含数字:

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

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

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

将您的afterTextChanged方法更改为:

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

在calculateResult()中,执行Integer.parseInt(s1); 无需检查字符串s1或s2是否为空?

因此,您不能将空String转换为Int。 尝试先检查s1或s2是否为空,然后再尝试将它们转换为Integers并进行计算...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM