0

I have to left pad 0's while printing it on console. Here I am reading number from a file.. The code is as below:

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);  }

In FormatNo.properties file I am storing TransNum=6 and RegId=56. The error what I am getting is

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String

2 Answers2

1

When you specify "d" in string format as here:

String R=  String.format("%02d", RegisId);

You have to provide integer as an argument and error message is saying you that: "d != java.lang.String".

The correct version should be:

String R = String.format("%02d", Integer.parseInt(RegisId));
kTT
  • 1,340
  • 11
  • 19
0

Supposing your numbers from 0 to 1000 are in transId and this format in Integer this will format with EXACT 4 positions so 0 will be 0000 and 999 will be 0999

String.format("%04d", Integer.parseInt(transId));

If there are problems with number formats in transId check here.

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109