如何打印此内容?
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
到目前为止我有这个:
int ROWS = 4;
int COLS = 4;
int[][] a2 = new int[ROWS][COLS];
String output = ""; // Accumulate text here (should be StringBuilder).
//... Print array in rectangular form using nested for loops.
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
output += " " + a2[row][col];
}
output += "\n";
System.out.print(output);
但它只是打印这个:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
我也想随机打印出数字。 我怎样才能做到这一点?
最佳答案
如果您希望它包含非零值,则需要填充a2
:
for (int col = 0; col < COLS; col++) {
a2[row][col] = row * COLS + col + 1; // <---- added this line
output += " " + a2[row][col];
}
另外:
- 您缺少一个右大括号。它应该位于
output += "\n";
之后。 ROWS++
的用途尚不清楚,而且看起来非常奇怪。
Also I want to print out the numbers at random. How can I do that?
三个简单步骤:
- 如上填充
a2
; - randomly shuffle
a2
; - 将其打印出来(您已经知道如何操作)。
关于java - 二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9192959/