HI all, I am a bit confused about right justifying and formatting strings and numbers in general, and I was wondering if somebody can clarify this for me please. Ok, so let's take an example:
// Fig. 7.2: InitArray.java
// Initializing the elements of an array to default values of zero.
public class InitArray
{
public static void main( String[] args )
{
int[] array; // declare array named array
array = new int[ 10 ]; // create the array object
System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
// output each array element's value
for ( int counter = 0; counter < array.length; counter++ )
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
} // end main
} // end class InitArray
Ok, so the first printf System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
prints off the string Index and the string Value with a field width of 8, meaning the the first character will be in 8th position (if you're ought to count the position), so the string index has 5 characters so the "V" of value will be positioned 3 characters after "Index":Index Value
The second System.out.printf( "%5d%8d\n", counter, array[ counter ] );
, on a separate line will start printing on the 5th character so the indexes are just below the 5th character which is the "x":
Index
0
The int instead has a field width of 8 charachters and will start printing at the 5+8th position, so 8 positions after the previous one (5).
SO,in the end in System.out.printf( "%5d%8d\n", counter, array[ counter ] );
the number 5 and 8 (or whatever number in their place) will always add up, and they give me an indication not only of hte field width but also where the characters will be printed. The count starts form 1 (and not 0) .
Correct?