2015-07-03 61 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

謝謝。當我讀取文件時,我的程序返回「」。該文件位於設備內部存儲器內部。它是否因爲我內部存儲的雙重價值而返回「」? –