错误:java.lang.NumberFormatException

时间:2014-02-22 04:54:03

标签: java parsing io numberformatexception

我在修复代码时遇到了困难。我收到的错误消息是:

线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“60 45 100 30 20”     at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)     在java.lang.Double.parseDouble(未知来源)     在Lab3.main(Lab3.java:15)

这是我的代码:

import java.io.*;
import java.math.*;

public class Lab3 
{
    public static void main(String[] args) throws IOException
    {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        double pVelocity, pAngle, tDistance, tSize, tElevation;
        double radians, time, height, pDistance;
        String input = br.readLine();

        String[] values = input.split("\\+");
        pVelocity = Double.parseDouble(values[0]);
        pAngle = Double.parseDouble(values[1]);
        tDistance = Double.parseDouble(values[2]);
        tSize = Double.parseDouble(values[3]);
        tElevation = Double.parseDouble(values[4]);

        while(pVelocity != 0 && pAngle != 0 && tDistance != 0 && tSize != 0 && tElevation != 0)
        {
            radians = pAngle*(Math.PI/180);
            time = tDistance/(pVelocity*Math.cos(radians));
            height = (pVelocity*time*Math.sin(radians))-(32.17*time*time)/2;
            pDistance = time*(pVelocity*Math.cos(radians));

            if(pVelocity*Math.cos(radians) == 0)
                System.out.print("The computed distance cannot be calculated with the given data.");
            else if(height > tElevation && height <= tSize)
                System.out.print("The target was hit by the projectile.");
            else if(height < tElevation)
                System.out.print("The projectile was too low.");
            else if(height > tSize)
                System.out.print("The projectile was too high.");
            else if(pDistance < tDistance)
                System.out.print("The computed distance was too short to reach the target.");
            else if(height < 0)
                System.out.println("The projectile's velocity is " + pVelocity + "feet per second.");
                System.out.println("The angle of elevation is " + radians +"degrees.");
                System.out.println("The distance to the target is " + tDistance + "feet.");
                System.out.println("The target's size is " + tSize + "feet.");
                System.out.println("The target is located " + tElevation + "feet above the ground.");
        }
    }
}

我相信我已经正确地将我的双变量解析为字符串变量,并且Eclipse在编译时没有显示更多错误。任何人都可以建议解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

您尝试解析"60 45 100 30 20"的输入不是数字。

尝试在空间上拆分输入并解析每个元素:

for (String s : input.split(" ")) {
    // parse s
}

也许你的意思是"\\s+"(一个或多个空格)而不是"\\+"(一个加号)。

答案 1 :(得分:3)

您错过了s中的input.split("\\+");。应该是input.split("\\s+");。你这样做的方式不会拆分任何东西,pVelocity"60 45 100 30 20",这不是一个数字,因此

java.lang.NumberFormatException: For input string: "60 45 100 30 20"