• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

examlab diagnostic test question 10

 
Fritz Guerilus
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can anyone help explain this output?


OUTPUT:
"1213%1$s"

Here's the explaination from exam lab:
"When using the printf method, the String formatting will be done for the first argument only. Other arguments will be considered as normal Strings, and they will not be formated"

What happended to "14%1$s" ?
How do you figure out which is the 1st argument?
In chapter 6's section on formating in K&B SCJP6 book, it doesn't show formating arguments for the printf() and format() methods in quotes("").

thank you
-Fritz
 
Fritz Guerilus
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Thanks Ireneusz. I looked up the links but I still cant seem to figure it out, but I'll continue to research it.
In the meantime, does anyone have a simple explaination of this issue?
-Thanks
-Fritz
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fritz, try to create a test program to see how the indexes work in the printf method, that will clear your doubt about how indexing works

 
indra negi
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but where are the args specified in the printf statement.



Here what I can get is only formats are specified.

I have understood what Ankit wants to say by using the following statement
 
Akanksha Mittal
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but where are the args specified in the printf statement.

view plaincopy to clipboardprint?
System.out.printf("12%1$s", "13%1$s", "14%1$s");
System.out.printf("12%1$s", "13%1$s", "14%1$s");

Here what I can get is only formats are specified.

I have understood what Ankit wants to say by using the following statement
view plaincopy to clipboardprint?
System.out.printf("%1$s","a","b");
System.out.printf("%1$s","a","b");




PrintStream java.io.PrintStream.printf(String format, Object... args)
Only the 1st argument is considered for formatting, rest all args are normal args.

try this:
System.out.printf("4","%1$s","b", 1, 2);

This will only print 4.
 
indra negi
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Akanksha then in the following snippet the output should only contain 12 and rest should have been discarded. Why does it take "13%1$s" in the output alongwith 12.




Please explain.
 
Piyush Porwal
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
%1 in the 'format' argument means replace %1 with first argument.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic