3

So I was trying to make some simple columns in Java (Yes, I am very new to this), and I just can't get it to 'stand' properly...

My code is the following:

int[][] grid = {
            {3, 5, 2434},
            {2, 4},
            {1, 2, 3, 4}
        };

combined with:

    for(int row=0; row<grid.length; row++){
        for (int col=0; col < grid[row].length; col++) {
            System.out.println(grid[row][col] + "\t");
        }

        System.out.println();
    }

Which gives me this result:

3
5
2434

2
4

1
2
3
4

Which leads me to my confusion.. Shoudn't "\t" just move them like "tab", instead of giving them a new line?

I appreciate the answers.

6 Answers 6

1

Use System.out.print instead of System.out.println. println automatically adds a linebreak and renders your tab useless.

for(int row=0; row<grid.length; row++){
    for (int col=0; col < grid[row].length; col++) {
        System.out.print(grid[row][col] + "\t");
    }

    System.out.println();
}
Sign up to request clarification or add additional context in comments.

Comments

1

you are using

System.out.println() ;

this method by default adds a new line at the end of the output.

if you don't want this behaviour use

System.out.print();

Comments

1
System.out.println(grid[row][col] + "\t");

You are using println which automatically adds a linefeed at the end of the String you pass it.

Try using System.out.print() instead.

Comments

1

The next line is because of the method println() and not because of \t use print() instead

Your method behaves as though it invokes print(yourParameters) and then println() which says

Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').

Source

Comments

0

Use System.out.print() instead of System.out.prinln() in order to avoid line feed

Comments

0

Use System.out.print(). the println command creates a new line at the end of every command , as if you wrote System.out.print(text+"\n").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.