不使用Double.parseDouble()将String Type转换为Double

时间:2015-03-12 11:34:20

标签: java string nullpointerexception type-conversion double

Double.parseDouble导致我的程序抛出一些NullPointerExceptions。有没有什么办法可以在不使用.parseDouble方法的情况下将String转换为double?

我知道String.format()可以用于Double to string,但是有相似之处吗?

编辑:

               try {
                    if(amountEntered != null || amountEntered == ""){
                       amntEntered = Double.parseDouble(amountEntered);
                    }
                    else{
                    //Do nothing   
                    textArea.setText("");
                    System.out.print("");
                    }
                } 
                  catch (NumberFormatException e) {

                    textArea.setText("");
                    System.out.print("");

                }

NullPointerException堆栈跟踪仍在打印。

2 个答案:

答案 0 :(得分:0)

尝试这个。在将其转换为double之前应用空检查。

String s="asdf";
    if(s!=null)
     Double d=Double.valueOf(s);

答案 1 :(得分:0)

首先,检查值是否为空。然后,如果您不想捕获NumberFormatExpression,请考虑使用正则表达式。以下是从http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#valueOf(java.lang.String)复制的解决方案:

为避免在无效字符串上调用此方法并抛出NumberFormatException,可以使用下面的正则表达式来筛选输入字符串:

final String Digits     = "(\\p{Digit}+)";
final String HexDigits  = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally
// signed decimal integer.
final String Exp        = "[eE][+-]?"+Digits;
final String fpRegex    =
  ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
   "[+-]?(" + // Optional sign character
   "NaN|" +           // "NaN" string
   "Infinity|" +      // "Infinity" string

   // A decimal floating-point string representing a finite positive
   // number without a leading sign has at most five basic pieces:
   // Digits . Digits ExponentPart FloatTypeSuffix
   //
   // Since this method allows integer-only strings as input
   // in addition to strings of floating-point literals, the
   // two sub-patterns below are simplifications of the grammar
   // productions from section 3.10.2 of
   // The Java™ Language Specification.

   // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
   "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+

   // . Digits ExponentPart_opt FloatTypeSuffix_opt
   "(\\.("+Digits+")("+Exp+")?)|"+

   // Hexadecimal strings
   "((" +
    // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
    "(0[xX]" + HexDigits + "(\\.)?)|" +

    // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
    "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +

    ")[pP][+-]?" + Digits + "))" +
   "[fFdD]?))" +
   "[\\x00-\\x20]*");// Optional trailing "whitespace"

if (Pattern.matches(fpRegex, myString))
    Double.valueOf(myString); // Will not throw NumberFormatException
else {
    // Perform suitable alternative action
}

如果表现并不重要,可能会尝试......捕捉是一个更好的解决方案。