I have a \"connect four board\" which I simulate with a 2d array (array[x][y] x=x coordinate, y = y coordinate). I have to use \"System.out.println\", so I have to iterate
//This is The easiest I can Imagine .
// You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns
for(int rows=0;rows<array.length;rows++){
for(int columns=0;columns <array[rows].length;columns++){
System.out.print(array[rows][columns] + "\t" );}
System.out.println();}
Just change the indexes. i and j....in the loop, plus if you're dealing with Strings you have to use concat and initialize the variable to an empty Strong otherwise you'll get an exception.
String string="";
for (int i = 0; i<array.length; i++){
for (int j = 0; j<array[i].length; j++){
string = string.concat(array[j][i]);
}
}
System.out.println(string)
Just invert the indexes' order like this:
for (int j = 0; j<array[0].length; j++){
for (int i = 0; i<array.length; i++){
because all rows has same amount of columns you can use this condition j < array[0].lengt in first for condition due to the fact you are iterating over a matrix
Consider it as an array of arrays and this will work for sure.
int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[i].length; j++) {
System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
}
}
Simple idea: get the lenght of the longest row, iterate over each column printing the content of a row if it has elements. The below code might have some off-by-one errors as it was coded in a simple text editor.
int longestRow = 0;
for (int i = 0; i < array.length; i++) {
if (array[i].length > longestRow) {
longestRow = array[i].length;
}
}
for (int j = 0; j < longestRow; j++) {
for (int i = 0; i < array.length; i++) {
if(array[i].length > j) {
System.out.println(array[i][j]);
}
}
}