从Android的一个EditText避免解析错误 [英] Avoiding a Parsing Error from an EditText in Android

查看:97
本文介绍了从Android的一个EditText避免解析错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要计算器社区, 我创造了这个方法,把部分的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;
    }
    双倍返还;
}
 

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

由于它抛出一个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.

这篇关于从Android的一个EditText避免解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆