逐列打印二维阵列



这个非常基本的代码逐行打印我的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

所以我试着把每列打印间隔半秒。

如果您想在计时器上打印出每一列,那么您需要使用三个循环。

您需要为每个迭代清除以前的控制台输出。如果通过命令行执行程序,以下代码在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();
    }
}

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

最新更新