java - 为什么在检查字符串是否可以是双精度时出现错误
问题描述
嘿,伙计们,我对编码很陌生,但我的一个项目是检查一个字符串是否可以解析成双精度。尝试运行程序时不断打印错误。
这是代码:
public static void main(String[] args) {
SimpleReader in = new SimpleReader1L();
SimpleWriter out = new SimpleWriter1L();
// Constant entered in by user as a string
out.println("Welcome to constant approximator");
out.println("Please enter in a constant to be estimated");
String realConstant = in.nextLine();
//Double variable created in order to reassign later
double test = 0;
//FormatChecker class and canParseDouble verifies if the string is truly a double. boolean method.
FormatChecker.canParseDouble(realConstant);
//Test reassign and converts
test = Double.parseDouble(realConstant);
out.print(test);
in.close();
out.close();
}
}
这是错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "pi"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at ABCDGuesser1Test.main(ABCDGuesser1Test.java:36)
解决方案
你应该使用canParseDouble()
不只是调用它的结果。像这样的东西,我认为:
if (FormatChecker.canParseDouble(realConstant)) {
test = Double.parseDouble(realConstant);
out.println(test);
}
推荐阅读
- javascript - 使用 nodejs/electron 添加新行导致添加多行
- python - Numpy / Scipy 不写入某些像素
- r - 寻找如何在 R(ClinVar 变体数据处理)中使用带有多个分隔符的单独()
- angular - 角度输入元素绑定不适用于对象。如何让它遵循 json 值?
- c# - Asp.Net Core 将 UTC (YYYY-MM-DDThh:mm:ss.sTZD) 输入转换为 LocalDateTime
- html - 如何使用媒体查询禁用部分 HTML?
- java - 将 XML 字符串解析为 org.w3c.dom.Document 的最快方法
- java - Android:按钮对点击没有反应
- c# - Is it better to put my logic in an event handler or in a setter for MVVM (Xamarin `Picker` `SelectedItem` quirks)
- javascript - 在 Node.js 和 Express 中将压缩文件流式传输到客户端,无需写入磁盘