2

So I've used this:

System.out.println("Of what race do you belong?\n[H]uman\t [E]lf\t [D]warf\t [O]rc\t [G]nome");

And gotten a print with very random spacing where \t has been placed. I've also used this same type of thing with this:

System.out.println("Which of the following are you?\n[W]arrior\t [R]ogue\t [M]agician");

And gotten perfectly spaced breaks for the \t. Any reason why it would give me such odd spacing with the 1st one?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Ryan Atkins
  • 23
  • 1
  • 3

5 Answers5

7

\t is tab. Open a regular text editor and check how a tab behaves. It indents to a certain position. It DOES NOT insert x number of spaces.

Ajk_P
  • 1,874
  • 18
  • 23
  • 1
    I should have realized this as it's very clear what tab does in notepad++. Thanks a ton for pointing out the obvious when I am oblivious. – Ryan Atkins Sep 09 '14 at 18:35
2

\t inserts a TAB character, not spaces. Knowing this, you should not use tabs to format the output of your data.

Since this looks for displaying data to user, it would be better using String#format which allows providing spaces to both left and right sides for your text.

Here's an example using %-15s:

//splitted in 2 lines for better understanding
String outputText = String.format("Of what race do you belong? %-15s %-15s %-15s %-15s %-15s",
    "[H]uman", "[E]lf", "[D]warf", "[O]rc", "[G]nome");
System.out.println(outputText);

Where:

  • %s means that it will add a String to the output.
  • 15 is the number of spaces to locate the string
  • - indicates it should be left aligned.

Output of code above:

Of what race do you belong? [H]uman         [E]lf           [D]warf         [O]rc           [G]nome

You can shorten the length of the spaces by just modifying the -15.

More info about how to proper format your output text:

Note that using System.out.printf uses Formatter behind the scene as well.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

The \t character is a tabulation character.

Subsequent tabs act "inconsistently", as in, they won't display the same amount of space.

You should use a regular number of spaces instead.

Something like:

System.out.println("Of what race do you belong?\n[H]uman   [E]lf   [D]warf   [O]rc   [G]nome");
Mena
  • 47,782
  • 11
  • 87
  • 106
0

When you use \t you are adding a tab and not a space.

drage0
  • 372
  • 3
  • 8
0

As others have said \t is tab and a space is always one column but tab could be a different number of columns depending on your environment.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331