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++;
}
}
}
Answer
You can use printf
which uses Formatter for padding here:
System.out.printf("%02d ", counter);
No comments:
Post a Comment