在控制台上打印时我必须留下 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
最佳答案
当您以字符串格式指定“d”时,如下所示:
String R= String.format("%02d", RegisId);
您必须提供整数作为参数,并且错误消息告诉您:“d!= java.lang.String”。
正确的版本应该是:
String R = String.format("%02d", Integer.parseInt(RegisId));
关于java - 从文件读取时如何将 0 填充到 1 到 1000 之间的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30433987/