如何在Java中檢查字串是否可以解析為double型別?


使用 parseDouble() 方法

**parseDouble()** 方法是 **java.lang.Double** 類的方法,它接受一個字串值,對其進行解析,並返回該字串的雙精度數值。

如果傳遞空值給此方法,它會丟擲 NullPointerException 異常;如果此方法無法將給定的字串解析為雙精度數值,它會丟擲 NumberFormatException 異常。

因此,要了解某個特定字串是否可以解析為 double 型別,可以將其傳遞給 parseDouble 方法,並將此行程式碼用 try-catch 塊包裹。如果發生異常,則表示給定的字串無法解析為 double 型別。

示例

 線上演示

import java.util.Scanner;
public class ParsableToDouble {
   public static void main(String args[]) {
      try {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a string value: ");
         String str = sc.next();
         Double doub = Double.parseDouble(str);
         System.out.println("Value of the variable: "+doub);
      }catch (NumberFormatException ex) {
         System.out.println("Given String is not parsable to double");
      }
   }
}

輸出

Enter a string value:
2245g
Given String is not parsable to double

使用 valueOf() 方法

類似地,Double 類的 **valueOf()** 方法(也)接受一個字串值作為引數,修剪多餘的空格並返回字串表示的雙精度數值。如果給定的值無法解析為 double 型別,此方法會丟擲 NumberFormatException 異常。

示例

 線上演示

import java.util.Scanner;
public class ParsableToDouble {
   public static void main(String args[]) {
      try {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a string value: ");
         String str = sc.next();
         Double doub = Double.valueOf(str);
         System.out.println("Value of the variable: "+doub);
      }catch (NumberFormatException ex) {
         System.out.println("Given String is not parsable to double");
      }
   }
}

輸出

Enter a string value:
2245g
Given String is not parsable to double

使用 Double 類的建構函式

Double 類的一個建構函式接受一個字串作為引數,並構造一個(Double)物件,該物件封裝了給定的值。如果傳遞給此建構函式的字串無法解析為 Double 型別,則會丟擲 NumberFormatException 異常。

示例

 線上演示

import java.util.Scanner;
public class ParsableToDouble {
   public static void main(String args[]) {
      try {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a string value: ");
         String str = sc.next();
         Double doub = new Double(str);
         System.out.println("Value of the variable: "+doub);
      }catch (NumberFormatException ex) {
         System.out.println("Given String is not parsable to double");
      }
   }
}

輸出

Enter a string value:
2245g
Given String is not parsable to double

更新於: 2019年10月11日

5K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告