生成int高达1亿的抛出异常

时间:2014-11-05 18:43:51

标签: java

我正在尝试生成高达1亿的整数,然后将其与预定义的整数/字符串组合。

  

示例:predefined = 1010生成:gen = 5020315 Combined =   10105020315

然后将该号码保存到.txt文件,因此文本文件应该有1亿行。

这是我写的代码:

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class exec{

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException
    {
        int initial = 6618;
        PrintWriter writer = new PrintWriter("variations.txt", "UTF-8");
        for(int a = 0; a < 100000000; a++){
            int a2 = Integer.parseInt(Integer.toString(initial) + Integer.toString(a));
            writer.println(a2);
        }
        writer.close();

    }

}

但它会引发以下错误:

  

线程“main”中的异常java.lang.NumberFormatException:用于输入   字符串:“6618100000”

为什么会这样?问题在哪里?

3 个答案:

答案 0 :(得分:2)

组合6618,其中a的值导致数字太大而无法保存在int变量中(例如,6618100000太大而无法保存在int变量中)。 int的最大值是2^31-1。您可以改为使用Long.parseLong()

答案 1 :(得分:2)

无论何时解析,都需要确保要从字符串创建的Integer小于Integer.MAX。

Integer.MAX等于2147483647,因此任何大于此值的值都会导致异常。

答案 2 :(得分:2)

你需要很长时间,你可以使用Long.parseLong();。 int的最大值是长2 ^ 31-1但是长的是2 ^ 63-1。