java - 逐列打印二维数组

标签 java arrays multidimensional-array

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

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

这些点代表的不是实际的空白,而是半秒的 sleep 时间。我想要输出的是

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

关于java - 逐列打印二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59277557/

相关文章:

java - 带附加文件的 If 语句

java - Java 库类的源代码

C++将数组元素向右推

c++ - 5 维 vector 声明

java - 两个迭代器抛出 ConcurrentModificationException

java - 外键作为 OpenJPA 中复合主键和 ManyToOne 关系的一部分

python - 查找并检查列表中的项目

PHP 数组使用 Laravel 合并到批量插入

c - 使用函数传递数组

javascript - 排序多维数组jquery/javascript