Java Double parseDouble()方法及示例
Java中Double类的 parseDouble() 方法是Java中的一个内置方法,它可以返回一个新的Double,初始化为指定的String所代表的值,正如 Double 类的valueOf方法所做的那样 。
语法
public static double parseDouble(String s)
参数: 它接受一个强制参数s,指定要解析的字符串。
返回类型: 它返回由字符串参数代表的 双倍 值。
异常: 该函数抛出两个异常,描述如下。
NullPointerException – 当解析的字符串为空时。NumberFormatException – 当解析的字符串不包含可解析的浮点数时。下面是上述方法的实现。
程序1 :
// Java Code to implement// parseDouble() method of Double class class GFG { // Driver method public static void main(String[] args) { String str = "100"; // returns the double value // represented by the string argument double val = Double.parseDouble(str); // prints the double value System.out.println("Value = " + val); }}
输出。
Value = 100.0
程序2: 显示NumberFormatException
// Java Code to implement// parseDouble() method of Double class class GFG { // Driver method public static void main(String[] args) { try { String str = ""; // returns the double value // represented by the string argument double val = Double.parseDouble(str); // prints the double value System.out.println("Value = " + val); } catch (Exception e) { System.out.println("Exception: " + e); } }}
输出。
Exception: java.lang.NumberFormatException: empty String
程序3: 显示NullPointerException
// Java Code to implement// parseDouble() method of Double class class GFG { // Driver method public static void main(String[] args) { try { String str = null; // returns the double value // represented by the string argument double val = Double.parseDouble(str); // prints the double value System.out.println("Value = " + val); } catch (Exception e) { System.out.println("Exception: " + e); } }}输出。
Exception: java.lang.NullPointerException
参考资料: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
