• Post Reply Bookmark Topic Watch Topic
  • New Topic

printf format string question  RSS feed

 
Kasun Liyanage
Greenhorn
Posts: 23
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi



This produces: > (123)<

i can't figureout how the space between > and ( is happened and the meaning of '7' in the format string.
Please explain.
Thanks.
 
alex cintea
Greenhorn
Posts: 9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int i1 = -123;
System.out.printf(">%1$(7d< \n", i1);

printf("format string", argument(s));
%[arg_index$][flags][width][.precision]conversion char

The formatting data always start with the % sign.

1$ - represents the first argument that should be printed

() - enclose negative numbers in parentheses

7d - means that the string will have the width of 7 integers

\n - escape character new line


Hope that this will help you.
 
Kasun Liyanage
Greenhorn
Posts: 23
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks it helped. But when i apply 7d, 9 characters are printed:

"> (123)< "
123456789


Why was that?
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only the argument gets formatted by the flags. You pass -123 into the format string and the 7d says to make the argument 7 characters long (and an integer). So the steps would be:
1) Format -123 so that negative numbers use parenthesis. Result: (123) (5 characters)
2) Format (123) so that it has a width of 7. Use spaces to fill the width. Result: __(123) (7 characters. Underscores used instead of spaces for display purposes)
3) Insert the formatted argument into the correct position of the format String. Result: >__(123)< \n (9 characters including the >< which were not part of the argument formatting. Plus 2 more characters (11 total) for final space and new line)
 
Kasun Liyanage
Greenhorn
Posts: 23
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That cleared it. Appreciate the help. Thanks!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!