promotion image of download ymail app
Promoted

[簡單Java]請問如何將String轉double

我想透過main傳入一個args[0]參數~型態一定是String~

但程式內有一參數是double型別的~

請問要如何將String的資料轉為double?

感激不盡!!

2 Answers

Rating
  • 1 decade ago
    Favorite Answer

    請參考 Double 類別:

    在 java.lang 這個封裝底下

    Double 的繼承關係:

     java.lang.Object

     └ extended by java.lang.Number

      └ extended by java.lang.Double

    所有 Double 繼承的介面:

     Serializable, Comparable<Double>

    Double 類別的宣告型態:

     public final class Double

      extends Number

      implements Comparable<Double>

    Since:

     JDK1.0

    注意到這個 Double 的成員方法:

    parseDouble

    public static double parseDouble(String s)

            throws NumberFormatException

     Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.

     Parameters:

      s - the string to be parsed.

     Returns:

      the double value represented by the string argument.

     Throws:

      NumberFormatException - if the string does not contain a parsable double.

     Since:

      1.2

    舉例:

    class A {

     public static void main (String args[]) {

      try {

       double num = Double.parseDouble (args[0]);

       num += 0.1;

       System.out.println (num);

      } catch (NumberFormatException nfe) {

       nfe.printStackTrace();

      }

     }

    }

    說明:

    num ← 把 args[0] 字串轉換成 Double 的型態

    num ← num + 0.1

    印出 num 的字串型態

    關於 try-catch:

    由於 parseDouble 會 throws NumberFormatException

    所以必須用 try 包住 parseDouble 方法

    字串轉換成 Double 的時候出現例外

    才跳到 catch NumberFormatException 的程式區段繼續執行

    Source(s): jdk_1_5_0-docs-api
    • Commenter avatarLogin to reply the answers
  • Sam
    Lv 4
    1 decade ago

    回得的真專業GOOD

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.