java解析字符串为double_如何在Java中检查字符串是否可解析为double?

使用parseDouble()方法

java.lang.Double类的parseDouble()方法接受一个String值,对其进行解析,然后返回给定String的double值。

如果将空值传递给此方法,则它将引发NullPointerException,并且如果此方法无法将给定的字符串解析为双精度值,则将引发NumberFormatException。

因此,要知道特定的字符串是否可以解析为双精度,请将其传递给parseDouble方法,并使用try-catch块包装此行。如果发生异常,则表明给定的String无法解析为两倍。

示例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()方法(也)接受String值作为参数,修剪多余的空格并返回由字符串表示的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类的构造函数之一接受String作为参数,并构造一个包装给定值的(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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值