java - 如何解析 String.format 将 0 添加到 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 之类的数据类型,具体取决于您要使用它做什么。
推荐阅读
- sms - 使用 AT 命令 SIM900A 获取 SMSC(短信中心)号码
- javascript - 如何进行包含数字和字符的 16 位查询?
- swift - Swift - RoaringBitmap - 序列化为 base64
- haxe - 什么可能导致网站内容在在线托管但在本地下载时无法正常工作?
- node.js - 如何在 Angular/Expressjs 中处理 404 异常处理
- javascript - 有没有办法在网页中声明所有 javascript http 请求必须只针对同一主机?
- docker - Bitbucket 找不到来自 hub.docker.com 的图像
- api - 如何处理来自 Dio post call 的错误信息?
- r - 等待未来在 Shiny 中结合进度条完成
- android - 按下“ENTER”时无法将焦点设置到下一个编辑文本