从文件中读取时如何将零填充到 1 到 1000 之间的数字?
How to left pad zeroes to number between 1 to 1000 while reading it from file?
在控制台上打印时,我必须离开 pad 0。这里我正在从文件中读取数字。代码如下:
public class FormatNumber {
public static void main(String[] args) {
Properties properties=new Properties();
File newFile=new File("FormatNo.properties");
try {
newFile.createNewFile();
properties.load(new FileInputStream(newFile));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String transId = properties.getProperty("TransNum");
System.out.println(transId);
String RegisId = properties.getProperty("RegId");
String R= String.format("%02d", RegisId);
System.out.println(R);
String T=String.format("%04d", transId);
System.out.println(T); }
在 FormatNo.properties 文件中,我存储了 TransNum=6 和 RegId=56。我得到的错误是
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
假设您从 0 到 1000 的数字在 transId
中并且这种格式在 Integer
中,这将格式化为 EXACT 4 个位置,因此 0
将是 0000
和 999
将是 0999
String.format("%04d", Integer.parseInt(transId));
如果transId
check here中的数字格式有问题。
当您以字符串格式指定 "d" 时:
String R= String.format("%02d", RegisId);
您必须提供整数作为参数,错误消息告诉您:"d != java.lang.String".
正确的版本应该是:
String R = String.format("%02d", Integer.parseInt(RegisId));
在控制台上打印时,我必须离开 pad 0。这里我正在从文件中读取数字。代码如下:
public class FormatNumber {
public static void main(String[] args) {
Properties properties=new Properties();
File newFile=new File("FormatNo.properties");
try {
newFile.createNewFile();
properties.load(new FileInputStream(newFile));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String transId = properties.getProperty("TransNum");
System.out.println(transId);
String RegisId = properties.getProperty("RegId");
String R= String.format("%02d", RegisId);
System.out.println(R);
String T=String.format("%04d", transId);
System.out.println(T); }
在 FormatNo.properties 文件中,我存储了 TransNum=6 和 RegId=56。我得到的错误是
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
假设您从 0 到 1000 的数字在 transId
中并且这种格式在 Integer
中,这将格式化为 EXACT 4 个位置,因此 0
将是 0000
和 999
将是 0999
String.format("%04d", Integer.parseInt(transId));
如果transId
check here中的数字格式有问题。
当您以字符串格式指定 "d" 时:
String R= String.format("%02d", RegisId);
您必须提供整数作为参数,错误消息告诉您:"d != java.lang.String".
正确的版本应该是:
String R = String.format("%02d", Integer.parseInt(RegisId));