首页 > 解决方案 > 为什么在检查字符串是否可以是双精度时出现错误

问题描述

嘿,伙计们,我对编码很陌生,但我的一个项目是检查一个字符串是否可以解析成双精度。尝试运行程序时不断打印错误。

这是代码:

        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)

标签: javaparsingnumberformatexception

解决方案


你应该使用canParseDouble()不只是调用它的结果。像这样的东西,我认为:

if (FormatChecker.canParseDouble(realConstant)) {
   test = Double.parseDouble(realConstant);
   out.println(test);
} 

推荐阅读