Angelo Nuho Angelo Nuho - 5 months ago 8
Java Question

Why My two dimencional array/ Matric it's printed wrong?

Why is not printed like a matrice? (I mean side by side.)
*Dont really know if there is a difference between two dimencional arrays and matrices as i can understand it seems there are the same thing to me.

import java.util.Arrays;

public class test {
public static void main (String[] args){

int array[][] = {{4,5,6},
{6,8,9}};

int array1[][] = {{5,4,6},
{5,6,7}};


Declaring how many rows and colons my first array has.

System.out.println("Number of rows = " +array.length);
System.out.println("Number of cols = " + array[0].length);


Printing the array.

int l = array.length;
int c = array[0].length;

System.out.println();

System.out.println("Print matrice : \n " );
for(int i=0; i<l; i++){
for(int j=0; j<c; j++){

System.out.println(" | " +array[i][j]+ " | ");
}
System.out.println(" \n");
}


}
}


Printing result :

Number of rows = 2
Number of cols = 3

Print matrice :

| 4 |
| 5 |
| 6 |


| 6 |
| 8 |
| 9 |

Answer

System.out.println automatically adds a line break. You could change both of your print statements to System.out.print, or change it to this:

for(int i=0; i<l; i++){
    for(int j=0; j<c; j++){
        System.out.print(" | " +array[i][j]+ " | ");
    }
    System.out.println();
}

System.out.println() will add the line-break without the need of the additional \n. (Note that this is also the reason why you are getting two line-breaks between your matrix rows).

Edit: If you don't want an empty new line, you should just go with the System.out.print() approach:

for(int i=0; i<l; i++){
    for(int j=0; j<c; j++){
        System.out.print(" | " +array[i][j]+ " | ");
    }
    System.out.print("\n");
}
Comments