如何解析 String.format 向 int 添加 0

How to Parse String.format added 0's to int

我想生成随机的国民身份证号码,当我用 String.format() 添加 0 来填充数字时,我无法将其解析回 int

public class NinGenerator {

        public static void Generator(sex name){ // sex is enum

        Random rand = new Random();

        int year = rand.nextInt(60) + 40;   // For starting at year 40
        int month, day, finalNumbers;

        month = rand.nextInt(12) + 1;

        if(name == sex.FEMALE){ // In case of female
            month += 50;
        }

        switch(month){  // For max number of days to match given month
        ```
        case 1:
        case 3:
            day = rand.nextInt(30) + 1;
        ```
        }

        finalNumbers = rand.nextInt(9999) + 1;  // last set of numbers

        String nin = FillZeroes(year, 2) + FillZeroes(month, 2) + FillZeroes(day, 2) + FillZeroes(finalNumbers, 4); // Merging it into string

        // Here occurs error

        int ninInt = Integer.parseInt(nin); // Parsing it into number

        while(ninInt % 11 != 0){    // Whole number has to be divisble by 11 without remainder
            ninInt++;
        }

            System.out.println("National identification number: " + ninInt);

    }

    public static String FillZeroes(int number, int digits){    // For number to correspond with number of digits - filling int with zeros

        String text = String.valueOf(number);

        if(text.length() < digits){

            while(text.length() != digits){
                text = String.format("%d1", number);
            }
        }

        return text;
    }

}

我想生成能被11整除的10位数字没有提醒,编译器总是在解析的那一行产生错误

我测试了你的代码,我相信你已经达到了 int 可以达到的极限。如果您尝试将“2147483647”作为您的 nin 值,它将 运行,但是一旦您转到“2147483648”,您将得到相同的错误。如果你想解决这个问题,你可能必须使用 long 或 double 等数据类型,具体取决于你想用它做什么。

Here is a link showing the different datatypes and their ranges.

您的 FillZeroes() 函数可以简单地是:

public static String FillZeroes(int number, int digits)
{
    String format = "d" + digits.ToString();
    return number.ToString(format);
}