首页 > 解决方案 > 如何逐行访问多维?

问题描述

我试图在java中逐行访问多维,但我无法实现它。

我有这段代码,但它逐列打印出数组:

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

所以,例如,如果我有这个数组:

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

我怎样才能以这种方式打印出来?

adg
beh
cfi

完整代码:

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]);
            }
        }
    }
}

标签: javaarraysmultidimensional-array

解决方案


你几乎做到了。只需更换:

System.out.print(array[i][j]);

对此:

System.out.print(array[j][i]);

UPD 1:
所以你的代码变成:

String[][] array = {{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}};
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();
}

推荐阅读