0

Possible Duplicate:
Left padding integers with zeros in Java

I need to add some leading zeros dynamically relative to input number length, for example if I input 10 the it will output

Numbers 01 02 03 04 05 06 07 08 09 10

I think the way to do it is to get the length of the numbers input and then apply that value to the counter using some formatting, just not sure the best way of going about that.

This is what I have so far.. (I am very new to programming)

    public static void main(String[] args) {
    int numbers;
    int counter = 1;
    int padlength;

    Scanner ngrabber = new Scanner(System.in);
    System.out.println("Please enter numbers to output number");
    numbers = ngrabber.nextInt();


                System.out.println("Numbers");
                while (counter <= numbers)          
                {
                    padlength = String.valueOf(numbers).length();
                    System.out.println(counter);
                    counter++;
                }


        }       
    }   
Community
  • 1
  • 1
MonkeyCMonkeyDo
  • 73
  • 2
  • 11

3 Answers3

2

You should use Java's printf style functions as shown here

System.out.printf("%02d ",counter);

Unless I am not clear of the syntax, The 2 will make sure that the length of the printed number is a min of 2, and the 0 means pad with 0 if the length of the input number is less than 2.


Edit: To change number dynamically, try this.

padlength = String.valueOf(numbers).length();
System.out.printf(String.format("\%0%dd " ,padlength),counter);
Karthik T
  • 31,456
  • 5
  • 68
  • 87
2

You can use printf which uses Formatter for padding here:

System.out.printf("%02d ", counter);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

printf is the right answer for Java.  If you ever find yourself needing to do this in a brain-dead environment (e.g., a Windows command script, a.k.a. batch file), here’s an approach:

Convert your upper bound number to a string; e.g., 10 –> "10"
Get the length of that string: strlen("10") = 2
Append that many zero characters (0) to a one character (1): strcat("1","0","0") = "100"
Convert that string to a number: "100" –> 100
For each number that you want to format: add the above number (1 + 100 = 101), convert to a string (101 –> "101"), and strip off the first character ("101" –> "01").

Yes, this is a kludge.  Anybody know a better way to do it on Windows?