Anon Ymous Anon Ymous - 1 year ago 128
Java Question

Java beginner - escape sequences

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");

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download