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?

the number 5 and 8 (or whatever number in their place) will always add up

What do you mean "add up"? They don't actually add, but they replace the %5d and %8d and put in spaces to fill up 5 or 8 characters
test it with System.out.printf("%05d - %08d", 50, 50); and it should fill up the unused spaces with 0's

I think you have it though :)

well by add up I mean that, like in the above example, the first number will print at position number 5 (by position I mean that if you count using the cursor if the output is in the terminal) and the second number, because it is is floated right is printed at position 13, so 8+5.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.