I want to count from 1
to 10
with a variable width.
Example for width: 4
Count Should Be:
0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 ---> Note that it's not 00010
Example for width: 2
Count Should Be:
01 ... 09 10 ---> Not 010
I've tried the following:
First attempt
for(int i = 1; i <= 10; i) {
System.out.println("0".repeat(width-1) i);
}
Second attempt
String output = String.format("d", 1);
These do not properly format numbers as the number of digits changes.
CodePudding user response:
You can create a format String with a variable length of format specifier. Adjust the width variable to whatever leading 0s you need.
int width = 2;
String format = "%0" width "d";
for(int i = 1; i <= 10; i ) {
String output = String.format(format, i);
System.out.println(output);
}
/* Output:
01
02
03
04
05
06
07
08
09
10
*/
CodePudding user response:
A more flexible approach will be to provide width
, start
and end
the sequence dynamically, so that none of the values will be hard coded.
A template for the output with the given width will be created by using string concatination.
public static void printZeroPaddedSequence(int start, int end, int width) {
String template = "%0" width "d ";
for (int i = start; i <= end; i ) {
System.out.printf("template", i);
}
}
public static void main(String[] args) {
printZeroPaddedSequence(1, 10, 4);
}
Output
0001 0002 0003 0004 0005 0006 0007 0008 0009 0010