Phil
Phil

Reputation: 11175

Simple formatting question in Java using printf

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.

Upvotes: 1

Views: 7075

Answers (2)

user85421
user85421

Reputation: 29680

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]);
    }

Upvotes: 0

BalusC
BalusC

Reputation: 1108632

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.

Upvotes: 4

Related Questions