【问题标题】:How to Parse String.format added 0's to int如何解析 String.format 将 0 添加到 int
【发布时间】:2019-04-30 20:18:16
【问题描述】:

我想生成随机的国民身份证号码,当我用 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位数字而不需要提醒,编译器总是在解析时产生错误

【问题讨论】:

  • 您是否尝试过 FillZeroes() 来检查它是否完成了它应该做的事情?
  • 请添加错误的nin 值。

标签: java string.format


【解决方案1】:

我测试了你的代码,我相信你已经达到了 int 可以达到多高的极限。如果您尝试将“2147483647”作为您的 nin 值,它将运行,但一旦您转到“2147483648”,您将收到相同的错误。如果您想解决此问题,您可能必须使用诸如 long 或 double 之类的数据类型,具体取决于您想要对其进行的处理。

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

【讨论】:

  • 是的,这是我忽略的问题,现在很简单,我所要做的就是使用 long ninInt = Long.parseLong(nin, 10);
【解决方案2】:

您的 FillZeroes() 函数可以是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 2014-01-07
    • 2020-12-20
    • 1970-01-01
    相关资源
    最近更新 更多