How to parse a double from EditText to TextView? (Android)

前端 未结 9 1252
时光取名叫无心
时光取名叫无心 2020-12-10 18:10

I\'m realy beginning to learn Java. When I run this code everything works fine till I leave my EditText boxes in the from empty and hit the run button. Then I get:

9条回答
  •  感动是毒
    2020-12-10 18:21

    Here is the JavaDoc for java.lang.Double class, parseDouble method:

    /**
     * Parses the specified string as a double value.
     * 
     * @param string
     *            the string representation of a double value.
     * @return the primitive double value represented by {@code string}.
     * @throws NumberFormatException
     *             if {@code string} is {@code null}, has a length of zero or
     *             can not be parsed as a double value.
     * @since Android 1.0
     */
    

    Empty values are not considered to be parseable. That's why you get this exception.

    You can intoduce an additional check to your code to see if string in the noKids EditText is empty and if so, manually set the value to 0.0:

    noKidsStr = noKids.getText().toString();
    
    if(noKidsStr == null || noKidsStr.isEmpty()) {
    
      etKids = 0.0;
    
    } else {
    
      etKids = Double.parseDouble(noKids.getText().toString());
    
    }
    

    I suggest writing some sort of convenience utility method that you can re-use for all similar situations in the future.

提交回复
热议问题