大输入的数字格式例外

时间:2013-10-26 13:55:55

标签: java netbeans biginteger numberformatexception

此代码适用于某些输入。 但是我得到一个NumberFormatError来获得更高的输入值,例如1000000。 输入(对于s [])的范围为1-2000000 可能是什么原因?

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

       try
        {
         BufferedReader read = new BufferedReader(new InputStreamReader(System.in));

         int no=Integer.parseInt(read.readLine());

         String s[]=read.readLine().split(" ");

         int result=0;

         for(int i=0; i<no; i++)
         {
             result+= Integer.parseInt(s[i]);
             if(result<0)
                 result=0;
         }
         System.out.println(result);

        }
        catch(IOException e)
       {
           System.out.println(e.getMessage());
       }
    }
}

3 个答案:

答案 0 :(得分:3)

在for循环中,您的第一个输入数字是数组的大小。到目前为止,这就是你的逻辑。除非您实际上手动加载2,000,000个数字(或复制/粘贴),否则会抛出ArrayIndexOutOfBoundsException

如果要键入非数字作为第二个输入,或者输入大于NumberFormatException(2147483647)或小于Integer.MAX_VALUE的数字(-2147483648),您将获得Integer.MIN_VALUE )。

输入类似的内容:

1000000
2 1 2 1 2 1 /*... 999990 digits later ...*/ 2 1 2 1

使程序正确终止。这是我使用的输入文件,如果有人想要的话:http://ge.tt/95Lr2Kw/v/0

该程序是从命令promt手动编译和运行的,如:java Solution < in.txt

编辑:我只记得数组中的输入值可能大到2000000.您必须使用BigInteger来保存result值大到2000000 ^ 2。< / p>

答案 1 :(得分:0)

我同意@lzmaki。 我的值没有得到任何NumberFormatException。 但是,我得到ArrayIndexOutofBoundException,当我尝试这样做时,它实际上是由StackOverFlow引起的:

1000000
1 2 3
then enter

就像那个时候一样,系统认识到它的堆栈中没有足够的内存来保存如此庞大的数据。

我遇到以下情况的NumberFormatException:

1000000
enter twice

因为没有系统获得非数字格式来转换整数格式,即“”。

我希望我的分析可以帮助您找到您的错误:)

答案 2 :(得分:0)

假设它不是缓冲区溢出,传递给Integer.parseInt的任何非数字字符都将抛出NumberFormatException。这包括空格和不可打印的字符,如换行符和小数点(因为浮点数不是整数)。

您可以尝试在调用.trim()时使用read.readLine()验证输入,并在传递给Integer.parseInt()之前检查空字符串或空字符串。类似的东西:

     String input = read.readLine();

     if ( input != null )
         input = input.trim();
     if ( input.equals("") )
         throw new IllegalArgumentException("Input must be a number");

     int no=Integer.parseInt( input );

但是,您决定验证第一行的输入,也执行第二次readLine()调用。希望您能够准确缩小造成问题的原因。