从Android的一个EditText避免解析错误错误、Android、EditText

2023-09-06 22:22:09 作者:回眸﹌泪倾城

要计算器社区, 我创造了这个方法,把部分的EditText场双打。我加入了if语句专门为避免语法错误,因为我知道,我的几个的EditText字段将留为空白的目的。然而,他们仍然保持在运行时来了。有谁知道,以避免解析字段是空白的正确方法?非常感谢你。

 专用双Doublify(EditText上EDITTEXT){
  如果(!(editText.getText()。等于(空))){
   返回Double.parseDouble(editText.getText()的toString());
  }
  返回0;
 }
 

解决方案

你为什么不尝试这样的事情?

 专用双Doublify(EditText上EDITTEXT){
    尝试 {
        双人大床= Double.parseDouble(editText.getText()的toString());
    }赶上(NumberFormatException异常E){
        返回0;
    }
    双倍返还;
}
 
android布局中一创建edittext就报错

编辑:请注意,这是未经测试......在这里没有编译器。 :(

由于它抛出一个NumberFormatException如果该字符串为空,正好赶上了异常,返回0,如果是无效或者格式不正确。

To stackoverflow community, I created this method to turn some EditText fields in doubles. I added the if statement specifically for the purpose of avoiding parse error because I know that several of my EditText fields will be left blank. However, they still keep coming at runtime. Does anybody know the correct way to avoid parsing fields that are blank? Thank you very much.

private double Doublify(EditText editText){
  if(!(editText.getText().equals(null))){
   return Double.parseDouble(editText.getText().toString());
  }
  return 0;
 }

解决方案

Why don't you try something like this?

private double Doublify(EditText editText) {
    try {
        Double double = Double.parseDouble(editText.getText().toString());
    } catch (NumberFormatException e) {
        return 0;
    }
    return double;
}

EDIT: Note, this is untested...no compiler here. :'(

Since it throws a NumberFormatException if the string is null, just catch the exception to return 0 if it's null or not formatted correctly.