Saturday, 5 May 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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...