Saturday, May 5, 2018

java - add leading zeros dynamically relative to input number





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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...