Printing with Argument Indices

An argument index is an optional decimal integer followed by a $ sign that indicates the position of the argument in the argument list. For example, lines 2021 and 2425 in Fig. 28.9 use argument index "1$" to indicate that all format specifiers use the first argument in the argument list. Argument indices enable programmers to reorder the output so that the arguments in the argument list are not necessarily in the order of their corresponding format specifiers. Argument indices also help avoid duplicating arguments. Figure 28.22 demonstrates how to print arguments in the argument list in reverse order using the argument index.

Figure 28.22. Reordering output with argument indices.

1 // Fig. 28.22: ArgumentIndexTest 2 // Reordering output with argument indices. 3 4 public class ArgumentIndexTest 5 { 6 public static void main( String args[] ) 7 { 8 System.out.printf( 9 "Parameter list without reordering: %s %s %s %s ", 10 "first", "second", "third", "fourth" ); 11 System.out.printf( 12 "Parameter list after reordering: %4$s %3$s %2$s %1$s ", 13 "first", "second", "third", "fourth" ); 14 } // end main 15 } // end class ArgumentIndexTest  

Parameter list without reordering: first second third fourth Parameter list after reordering: fourth third second first  

Категории