jonnybobonny
jonnybobonny

Reputation: 63

Left and right justifying using formatter in java- can't figure out how to format properly

I'm working on outputting elements of arrays and left/right justifying them appropriately, however I'm having difficulty getting the output to align properly. This is my output as of right now-

Houston      TX   2009834
Detroit      MI    925051
Indianapolis   IN    783612
Washington   DC    570898
Burlington   VT    180000

as you can see, the third line is off by a couple spaces. is there a way to specifically access this line of output and format it properly? My line to print is this-

for(int i = 0; i < pop.length; i++){
        System.out.printf("%-10s%5s%10d\n", city[i], state[i], pop[i]);
    }

Upvotes: 1

Views: 38

Answers (1)

Simon
Simon

Reputation: 6363

Try increasing number of characters indicated in your printf in

"%-10s%5s%10d\n"

This pads city names to 10 characters. Change it to

"%-15s%5s%10d\n"

To be able to handle city names up to 15 characters (or whatever length you want).

Upvotes: 1

Related Questions