How to print Two-Dimensional Array like table

后端 未结 15 1111
一整个雨季
一整个雨季 2020-11-30 06:55

I\'m having a problem with two dimensional array. I\'m having a display like this:

1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 . . . etc

What basi

15条回答
  •  孤城傲影
    2020-11-30 07:16

    This might be late however this method does what you ask in a perfect manner, it even shows the elements in ' table - like ' style, which is brilliant for beginners to really understand how an Multidimensional Array looks.

    public static void display(int x[][])   // So we allow the method to take as input Multidimensional arrays
        {
            //Here we use 2 loops, the first one is for the rows and the second one inside of the rows is for the columns
            for(int rreshti = 0; rreshti < x.length; rreshti++)     // Loop for the rows
            {
                for(int kolona = 0; kolona < x[rreshti].length;kolona++)        // Loop for the columns
                {
                    System.out.print(x[rreshti][kolona] + "\t");            // the \t simply spaces out the elements for a clear view   
                }
                System.out.println();   // And this empty outputprint, simply makes sure each row (the groups we wrote in the beggining in seperate {}), is written in a new line, to make it much clear and give it a table-like look 
            }
        }
    

    After you complete creating this method, you simply put this into your main method:

    display(*arrayName*); // So we call the method by its name, which can be anything, does not matter, and give that method an input (the Array's name)
    

    NOTE. Since we made the method so that it requires Multidimensional Array as a input it wont work for 1 dimensional arrays (which would make no sense anyways)

    Source: enter link description here

    PS. It might be confusing a little bit since I used my language to name the elements / variables, however CBA to translate them, sorry.

提交回复
热议问题