Issue
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("%04d", 1);
These do not properly format numbers as the number of digits changes.
Solution
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
*/
Answered By - Abdullah Leghari Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.