逐列打印2D数组

时间:2016-04-05 22:12:05

标签: java arrays multidimensional-array

这个非常基本的代码逐行打印我的2D数组。

public class scratchwork {
    public static void main(String[] args) throws InterruptedException {
        int[][] test = new int[3][4];

        for (int row = 0; row < 3; row++) {
            for (int col = 0; col < 4; col++) {
                System.out.print(test[row][col] = col);
            }

            Thread.sleep(500);
            System.out.println();
        }
    }
}

如何编辑循环以逐列打印数组?

编辑:只是想澄清输出是

0123

....

0123

....

0123

用点表示不是实际的空白区域而是半秒的睡眠时间。我试图输出的是

0...1...2...3
0...1...2...3
0...1...2...3

所以我试图将这些列彼此分开打印半秒。

2 个答案:

答案 0 :(得分:0)

您只需要更改嵌套循环的顺序。如果要一次打印列,则列必须是最外面的循环变量 只要考虑内循环将在每个外循环中执行多次。

答案 1 :(得分:0)

如果要在计时器上打印每列,则需要使用三个循环。

您需要清除每次迭代的前一个控制台输出。如果通过命令行执行程序,则以下代码适用于Windows。当然,这是特定于平台的,但有很多有用的答案,在Stack Overflow上,以及其他站点可以帮助您清除控制台输出。

import java.io.IOException;

public class ThreadSleeper {
    public static final int TIMEOUT = 500;
    public static final int ROWS = 3, COLS = 4;
    static int[][] test = new int[ROWS][COLS];

    public static void main(String[] args) {
        // Populate values.
        for (int i = 0; i < ROWS * COLS; i++) {
            test[i / COLS][i % COLS] = i % COLS;
        }
        try {
            printColumns();
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
    }

    public static void printColumns() throws InterruptedException, IOException {
        for (int counter = 0; counter < COLS; counter++) {
            clearConsole(); // Clearing previous text.
            System.out.printf("Iteration #%d%n", counter + 1);
            for (int row = 0; row < ROWS; row++) {
                for (int col = 0; col <= counter; col++) {
                    System.out.print(test[row][col] + "...");
                }
                System.out.println();
            }
            Thread.sleep(TIMEOUT);
        }
    }

    // http://stackoverflow.com/a/33379766/1762224
    protected static void clearConsole() throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
}
相关问题