创建一个方法,试图把字符串转换成double型的数值,在可能会出现问题时抛出一个异常(NumberFormatException)。采用适当的捕获机制来捕获异常。
/**
* @author huazie
* @version 2.0.0
* @since 2.0.0
*/
public class Test {
public static void main(String[] args) {
String str = "111a";
double num = convert(str);
System.out.println(num);
}
public static double convert(String str) {
double num = 0;
try {
num = Double.parseDouble(str);
} catch (NumberFormatException e) {
// 转换异常
System.out.println("转换失败");
}
return num;
}
}
你可以提前判断一下字符串能不能转成数字就行了,网上有很多方法,比如 https://www.likecs.com/show-308276678.html