How to access to a multidimensional row by row?

Adrian2895 :

I am trying to access to a multidimensional row by row in java but I am unable to achieve it.

I have this code but it prints out the array column by column:

for(int i = 0; i<array.length; i++) {
    for(int j = 0; j<array[i].length; j++) {
        System.out.print(array[i][j]);
    }
}

So, for instance if I have this array:

[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]

How can I print it out in this way?

adg
beh
cfi

Full code:

import java.util.Scanner;

public class forcabruta {
    public static void main (String[] args) {
        Scanner keyboard = new Scanner(System.in);
        char[] words = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '};
        String text;
        System.out.print("Enter a text to decode: ");
        text = keyboard.nextLine();
        char[][] combinations = new char[text.length()][words.length];
        for(int i = 0; i<text.length(); i++) {
            for(int j = 0; j<words.length; j++) {
                if(words[j] == text.charAt(i)) {
                    for(int k = 1; k<words.length; k++) {
                        combinations[i][k] = words[Math.floorMod(j-k, 27)];
                    }

                }
            }
        }
        for(int i = 0; i<combinations.length; i++) {
            for(int j = 0; j<combinations[i].length; j++) {
                System.out.print(combinations[j][i]);
            }
        }
    }
}
Hermueller :

Be careful of switching index!

For example, this would throw an error.

String[][] array = {{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}, {"j", "k"}};

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

Better is this:

String[][] array = {{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}, {"j", "k"}};

int maxColCount = 0;
int i = -1;
do {
    i++;
    for(int j = 0; j < array.length; j++) {
       if (array[j].length > i) {
          System.out.print(array[j][i]);
       }
       if (array[j].length > maxColCount) {
          maxColCount = array[j].length;
       }
    }
    System.out.println();
} while (i < maxColCount);

The basic idea is that you don't know how many columns you have, you will have to find it out yourself while doing the work. But you also have to check each time if the current row has so many columns or not before accessing it.

If the amount of columns is always the same, this should suffice.

String[][] array = {{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}};
for(int i = 0; i < array[0].length; i++) {
    for(int j = 0; j < array.length; j++) {
        System.out.print(array[j][i]);
    }
    System.out.println();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327656&siteId=1