0

I'm new in java programming and there's something confusing me with /t escape sequence. I tried to write the code for multiplication table:

for(int i = 1; i<=10; i++){
   for(int j = 1; j<=5; j++){
       System.out.println(j + "*" + i + "=" + j*i + "\t"); 
   }
   System.out.println();
}

How come that the ouput is like this:

enter image description here

I mean, why isn't the tab "the same size" in every case, i.e. 1x1=1 is quite far from 1x2=2, but 10x1=10 and 10x2=20 is closer. Also, when I try to do something like this in the code:

System.out.println(j + "*" + i + " = " + j*i + "\t"); 

(notice the spaces in both sides of equal sign), the output messes up:

enter image description here

Anon Ymous
  • 215
  • 1
  • 3
  • 7
  • You seem to be misundertanding the meaning of "tab". Tab is not a certain number of spaces wide, but it's used for alighning text, which it does in your code. – tobias_k Aug 31 '16 at 11:02
  • You should look up the function of a "tab". It's the same concept as in text editing software like Word. – QBrute Aug 31 '16 at 11:03
  • Your second output is messed up because some of the texts are exactly as wide as a tab, so in some cases it skips to the tab position at column 8, and in others to column 16. – tobias_k Aug 31 '16 at 11:04
  • Tab works the same in any word processor. If text before `\t`is longer than the set tab-position, the tab jumps to the next tab-position. – Markus Mitterauer Aug 31 '16 at 11:13
  • Different editors, consoles, etc., treat tabs a little differently, and the behaviour also depends on the font. Generally there is a notion of a “tab stop” to define the columns and column widths. A tab is as wide as the distance to the next tab stop. Sometimes there is an additional requirement that it is at least as wide as a space (so you end up at the *next* tab stop), sometimes the width is allowed to 0. All of this really hasn’t got anything to do with Java or the \t escape. On a console with monospace font, it usual to have a tab stop for every 8 character positions. – Ole V.V. Aug 31 '16 at 11:19
  • https://en.wikipedia.org/wiki/Tab_stop – Ole V.V. Aug 31 '16 at 11:20

1 Answers1

7

By default, tabulators (\t) form a "table", so columns with a fixed size (tab width). In a console, spaces are added until the next column starts.

If your text is wider than (or as wide as) a column (as in your second example), then the next column will be skipped (that's why an additional column is added) and the result looks a little strange.

You can try it out with a simple text editor, just press the tabulator key and you will see the same behavior:

a       b       c
looooooong      d       e
Tobias
  • 7,723
  • 1
  • 27
  • 44