printf in Java - What is% 3d for?

8

I'm seeing a java arrays exercise, but I can not figure out what the %3d is, if it's a int .

for (i=0; i<n; i++) {
    System.out.printf("a[%d] = %3d   b[%d] = %3d\n", i, a[i], i, b[i]);
}
    
asked by anonymous 12.02.2016 / 18:25

2 answers

10

% wc is used to format integer variables, it can basically be used as follows:

  • %d - formats an integer variable with how many digits there are;

  • %d - formats an integer variable with how many digits there are, but if the variable has an amount less than 4 digits, fill in the missing digits with zeros on the left.

Examples:

  • %4d applied to 1234 would be 1234;

  • %04d applied to 123 get 0123.

See an example: link

    
12.02.2016 / 18:34
6

The explanation of %3d can be divided as follows:

  • % print a variable here,
  • 3 use at least 3 characters to display, filling in spaces if necessary,
  • d the variable is of type int .

See a demonstration example on Ideone .

Source: What does "% 3d" mean in a printf statement?

    
12.02.2016 / 18:39