问题
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?
Edit: just want to clarify that the output is
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.
回答1:
If you want to print out each column on a timer, then you will need to use three loops.
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();
}
}
回答2:
You just need to change the order of the nested loops. If you want to print them columns at a time, then columns need to be the outermost looping variable.
Just consider that the inner loop will be executed multiple times per outer loop.
来源:https://stackoverflow.com/questions/36438000/print-a-2d-array-column-by-column