hello.
i have created String name,surname,country;
int age;
and a scanner which takes informations from keyboard.
and this print lines:
System.out.println("Name\t Surname\t Age\t Country);
System.out.println(name+"\t"+surname+"\t"+age+"\t"+country);
NORMALLY:

EX:
Name Surname Age Country
JOHN smith 35 uk

but IF NAME HAS TOO MANY CHARS IT IS NOT DISPLAYED IN THE SAME COLUMN.
EX:
Name Surname Age Country
MARTIN TIMBERLAKE 35 CALIFORNIA

IS POSSIBLE IN JAVA TO FIX THIS ?

Dani AI

Generated

Good tip from — the root cause is using tabs: they jump to tab stops, so long names push later columns out of alignment. For stable columns use fixed-width fields via Java's formatting (printf / String.format / Formatter) rather than manual tabs or concatenation.

Example (left-justified columns, age right-justified):

System.out.printf("%-12.12s %-15.15s %3d %-15.15s%n",
                  name, surname, age, country);

Explanation: %-12.12s left-justifies a string in a 12-char field and truncates any excess; %3d prints an int in a 3-character-wide field; %n is a newline. Remove the .12 precision if you prefer no truncation, or increase the widths to fit your data.

If you have many rows, compute column widths from the data and build the format string dynamically:

int nameW = Math.max("Name".length(), maxNameLength);
int surW  = Math.max("Surname".length(), maxSurnameLength);
int ctrW  = Math.max("Country".length(), maxCountryLength);

String fmt = "%-" + nameW + "s %-" + surW + "s %3d %-" + ctrW + "s%n";
System.out.printf(fmt, "Name", "Surname", "Age", "Country");
for (Record r : records) {
    System.out.printf(fmt, r.name, r.surname, r.age, r.country);
}

Quick troubleshooting: if alignment still looks off, confirm the console uses a monospaced font and you’re counting characters you expect (Unicode/wide characters can break visual width). For non-console output (GUI, HTML), use table widgets or HTML tables instead of formatted text.

Recommended Answers

All 2 Replies

yep, with formatting.
there are several ways of doing that, manually by setting a number of chars,
but if you want a decent way, I would suggest you read on about Formatted Printing.

commented: thx :) +1

thx ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.