Aligning a table in a java array
My code:
// 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 the output at the same interval
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
source to share
As said in this answer (slightly modified):
Use System.out.format . You can set the lengths of such fields:
System.out.format("%32s%10d%16d", name[index], sales[index], comm[index]);
These are spacers
name[index]
,sales[index]
andcomm[index]
up to 32, 10, and 16 characters, respectively.See the Javadocs for java.util.Formatter for more information on syntax (
System.out.format
usesFormatter
internally).
source to share
You can do something like
for (int index = 0; index < 5; index++) { // for loop for displaying multiple values
int numOfSpaces = 20 - name[index].length();
String spaces = "";
for (int i = 0; i<numOfSpaces; i++)
spaces += " ";
System.out.println("\t\t" + name[index] + spaces + "$" + sales[index] + "\t\t\t" + "$" + comm[index] + " ");
}
And change the arbitrary 20 to whatever you want eg. longest string in names + 5.
source to share