views:

273

answers:

2

I have an array of 12 numbers

int ary2[] = {3,5,9,11,15,18,22,23,30,31,35,39};

I want to print the numbers out with 2 places for the number and a space between the numbers.

Example print out would be :

 3  5  9 11 15 18 22 23 30 31 35 39

This is how far I got.

for(int i = 0; i < ary2.length; i++)
{
    System.out.printf("%-3s", ary2[i]);
}

I'm new at this. Although I won't be directly submitting this as homework, it is affiliated with a homework project of mine; therefore, i'll be using that homework tag anyways.

EDIT: Answer Found.

+2  A: 

I am not quite sure if I understand the question. Your code example look like to already do that. Or do you want to treat them as digits (align right)? If so, then you need %d instead (digit) of %s (string). See if the following suits your needs:

System.out.printf("%2d ", ary2[i]);

This would print:

 3  5  9 11 15 18 22 23 30 31 35 39

instead of what your original code did:

3  5  9  11 15 18 22 23 30 31 35 39

you only have to live with the trailing space ;)

You can find more formatting rules in the java.util.Formatter API.

BalusC
But as you can see, there is 2 spaces in between the first 2 letters 3 and 5.
Phil
And thanks for the API link
Phil
You literally said, you wanted 2 places for the number? What do you mean with that then?
BalusC
A: 

Not sure what the problem is, reading the other answers and comments, I suspect that you want to display the numbers 0-padded:

    System.out.printf(" %02d", ary2[i]);

not 0-padded, 2 "places", like other already wrote:

    System.out.printf(" %2d", ...

I put the spaces at the start... but just my preferences

you can use some other character as separator insted of the space to see what's going on.
Something like System.out.printf("^%2d", ary2[i]);

If you want to avoid the space at the start or end of the line, you must split the output

    System.out.printf("%2d", ary2[0]);  // no space here
    for(int i = 1; i < ary2.length; i++)
    {
        System.out.printf(" %2d", ary2[i]);
    }

or do something like that (not my preferred)

    for(int i = 0; i < ary2.length; i++)
    {
        System.out.printf("%s%2d", (i == 0 ? "" : " "), ary2[i]);
    }
Carlos Heuberger