如何解析String.format将0添加到int

问题描述 投票:2回答:2

我想生成随机的国家识别号码,当我用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;
    }

}

我希望生成10位数字,可以被11整除而不需要提醒,编译器总是会在解析时生成错误

java string.format
2个回答
2
投票

我测试了你的代码,我相信你达到了int可以达到的极限。如果您尝试将“2147483647”作为您的nin值,它将会运行,但只要您转到“2147483648”,您将收到相同的错误。如果要修复此问题,可能必须使用数据类型,例如long或double,具体取决于您要对其执行的操作。

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


0
投票

你的FillZeroes()函数可能只是:

public static String FillZeroes(int number, int digits)
{
    String format = "d" + digits.ToString();
    return number.ToString(format);
}
© www.soinside.com 2019 - 2024. All rights reserved.