gpt4 book ai didi

java - 逐列打印二维数组

转载 作者:行者123 更新时间:2023-12-01 19:29:13 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com