Page 1 of 1

About Question enthuware.ocpjp.v7.2.1622 :

Posted: Sat Sep 14, 2013 8:34 am
by sinapse
System.out.printf("%1$s %2$s %s", "A", "B", "C");

"In this case, it starts with the last %s. Therefore, it prints the first argument which is A."should

If it is like you say it should print "A" "A" "B".

Can you help me here ? This is the hardest form to understand...

Re: About Question enthuware.ocpjp.v7.2.1622 :

Posted: Sat Sep 14, 2013 8:37 am
by sinapse
And this should print:

System.out.printf("%2$s %2$s %s", "A", "B", "C");

A B B

which is not true .!

Re: About Question enthuware.ocpjp.v7.2.1622 :

Posted: Sat Sep 14, 2013 8:44 am
by admin
sinapse wrote:System.out.printf("%1$s %2$s %s", "A", "B", "C");

"In this case, it starts with the last %s. Therefore, it prints the first argument which is A."should

If it is like you say it should print "A" "A" "B".

Can you help me here ? This is the hardest form to understand...
There are three formatters in the printf:
1. %1$s : This uses explicit indexing. So it will print the argument at that given index, which is 1. So it will print A.

2. %2$s : This uses explicit indexing as well. So it will print the argument at that given index, which is 2. So it will print B.


and 3. %s : This uses ordinary indexing. Also, this is the first place where ordinary indexing is being used, so the ordinary index will start with 1 here. So it will print the argument at 1. So it will print A.


HTH,
Paul.

Re: About Question enthuware.ocpjp.v7.2.1622 :

Posted: Sat Sep 14, 2013 8:47 am
by admin
sinapse wrote:And this should print:

System.out.printf("%2$s %2$s %s", "A", "B", "C");

A B B

which is not true .!
Not sure how you are interpreting the explanation. It says, "the ordinary index starts with the first format specifier that does not use explicit index."

In your example, ordinary index starts from the third piece of the whole string "%2$s %2$s %s" i.e. %s. So it will print A. The first two i.e. %2$s %2$s are using explicit indexing with a value 2, so they will print B and B. Thus, the whole string will print. B B A.

HTH,
Paul.

Re: About Question enthuware.ocpjp.v7.2.1622 :

Posted: Wed Feb 05, 2014 4:54 pm
by EpicWestern
I had this same problem but figured out. Its confusing because the language seems to imply that ordinary indexing gets priority over explicit indexing, and that "it starts with the last %s" refers to the indexing process as a whole not specifically the ordinary indexing part.

Also "Therefore, it prints the first argument which is A" adds to that confusion since it fails to mention that two other values were printed out first.

Re: About Question enthuware.ocpjp.v7.2.1622 :

Posted: Thu Apr 02, 2015 1:27 pm
by ThufirHawat
This is poor documented by Java (in my opinion).
Tnx for Paul, I understood here only.