2015-07-03 83 views
-2

我想知道如果我转换这会发生:Java“的”转换为double

String ret = ""; 

双:

Double.parseDouble(ret); 

当我运行的问题,我有一个错误说无效双:“”

+7

如果你想弄清楚自己,为什么问这里? – Eran

+2

什么阻止你发现? –

+0

[Double.parseDouble(string)和Double.valueOf(string)之间的区别是什么?](http://stackoverflow.com/questions/10577610/what-is-difference-between-double-parsedoublestring-and -double-valueofstring) – ganeshvjy

回答

0

请参见下面的Java的实现Double.parseDouble

public static double parseDouble(String s) throws NumberFormatException { 
    return FloatingDecimal.readJavaFormatString(s).doubleValue(); 
} 

现在检查下面的代码FloatingDecimal.readJavaFormatStringhere

in = in.trim(); // don't fool around with white space. throws NullPointerException if null 
     int l = in.length(); 
     if (l == 0) throw new NumberFormatException("empty String"); 

要回答你的问题:既然你逝去的空字符串,你会得到NumberFormatException

例外,你会得到如下。注意消息(“空字符串”)与我的第二个代码片段中可以看到的相同。

Exception in thread "main" java.lang.NumberFormatException: empty String 
+0

你是否得到了答案?如果不是那么请写你自己的答案,以便其他人可以从中受益.. http://stackoverflow.com/help/accepted-answer – hagrawal

0

它会抛出一个异常java.lang.NumberFormatException

0

如果您尝试运行代码

String ret = ""; 
double a = Double.parseDouble(); 

编译器将抛出一个java.lang.NumberFormatException,这意味着,在普通的术语,你给程序的输入类型不能被转换为双。如果你想解决这个问题,那么就给程序一个可解析的字符串(即6或3.24)。如果给出错误的输入,您也可以使用trycatch来引发不同的错误消息。

实施例:

public class Testing { 

    public static void main(String[] args) { 

     try{ 

      String ret = ""; 
      double a = Double.parseDouble(ret); 

     }catch(NumberFormatException e){ 

      System.out.println("Your error message here"); 
      //do something (your code here if the error is thrown) 

     } 
    } 
} 

这将打印出Your error message here,因为输入“”不能被转换为一个双。

更多关于NumberFormatException:Click here

有关解析字符串的更多信息:Click here

更多关于try and catch:Click here

+0

谢谢。当我读取文件时,我的程序返回“”。该文件位于设备内部存储器内部。它是否因为我内部存储的双重价值而返回“”? –