Snailwalker Snailwalker - 19 days ago 6
Java Question

How do I use String.format to display value with leading space?

I am trying to counting a number from 1 in an ascending order and I need to add leading space to each line, the trick is that there is no space for the first line, 1 space for the second number, 2 spaces for the third line and n spaces for the (n + 1)th number.

For example if user inputs value 4 , The expected output in the consle should be : enter image description here

I have done some research, I couldn't figure it out. I think it's related to String.format method. Any ideas? Your effort will be greatly appreciated!

int c = 0 ;
int num = input.nextInt();
input.close();
while (c < num)
{
c++;
System.out.println(String.format("%"+3+"s",c)); //this code gives the same length of leading space on everyline which is not what i want.

}

Answer
 public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
      int c = 0 ;
    int num = input.nextInt();
    input.close();
    while (c < num)
    {
        c++;
   System.out.println(String.format("%"+c+"s",c)); 
    }
}

instead of 3 use c

Comments