逐列打印2D数组 [英] Print a 2D array column by column

查看:86
本文介绍了逐列打印2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此非常基本的代码逐行打印我的2D数组.

This very basic code prints my 2D array row by row.

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

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

How can I edit the loops to print the array column by column?

只想弄清楚输出是

0123

....

0123

....

0123

点表示的不是实际的空白,而是半秒的睡眠时间.我想输出的是

with the dots representing not actual white space but the half second sleep time. What I'm trying to output is

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

因此,我尝试将各列彼此间隔半秒打印一次.

So I am trying to print the columns a half second apart from each other.

推荐答案

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

If you want to print out each column on a timer, then you will need to use three loops.

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

You will need to clear out the previous console output for each iteration. The following code works in Windows if you execute the program through the command line. Of course, this is platform specific, but there are many helpful answers, here on Stack Overflow, and other sites to help you clear console output.

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

这篇关于逐列打印2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆