Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alignment of table in array java [duplicate]

My code is this:

// for loop for displaying multiple values
for (int index = 0; index < 5; index++) { 

    System.out.println("\t\t" + name[index] + "\t\t\t" + "$" + sales[index] + "\t\t\t" + "$" + comm[index] + " ");
}

This is the current output, but I want to display output with same spacing

             Sales and Commission
    ======================================================
     Salesperson        Sales Amount        Commission
    -----------------------------------------------------
    u ujuhygtfd         $89000          $8900.0 
    uh uh           $87000          $8700.0 
    t t         $65000          $5200.0 
    f f         $54000          $4320.0 
    u r         $43000          $2580.0 

     Total: 9 Data entries

How can I display my data like this?

             Sales and Commission
    ======================================================
     Salesperson        Sales Amount        Commission
    -----------------------------------------------------
    u ujuhygtfd         $89000          $8900.0 
    uh uh               $87000          $8700.0 
    t t                 $65000          $5200.0 
    f f                 $54000          $4320.0 
    u r                 $43000          $2580.0 

     Total: 9 Data entries 
like image 364
kaushal garg Avatar asked Apr 09 '26 09:04

kaushal garg


1 Answers

As said in this answer (slightly modified):

Use System.out.format. You can set lengths of fields like this:

System.out.format("%32s%10d%16d", name[index], sales[index], comm[index]);

This pads name[index], sales[index], and comm[index] to 32, 10, and 16 characters, respectively.

See the Javadocs for java.util.Formatter for more information on the syntax (System.out.format uses a Formatter internally).

like image 99
serv-inc Avatar answered Apr 11 '26 22:04

serv-inc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!