我该如何打印?
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
另外,我想随机打印出这些数字。 我怎么能这样做?
答案 0 :(得分:3)
如果您希望它包含非零值,则需要填充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++
的目的不明确,看起来非常奇数。另外,我想随机打印出这些数字。我怎么能这样做?
三个简单的步骤:
a2
; a2
; 答案 1 :(得分:0)
a2[row][col] = row * COLS + col + 1;
ROWS++
Collections.shuffle
,然后将行和列分组答案 2 :(得分:0)
你的数组是空的
尝试直接初始化:
int[][] a2 = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
代码中的某些错误:试试这个:
int ROWS = 4;
int COLS = 4;
int[][] a2 = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
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);
答案 3 :(得分:0)
根据您的期望得到结果....
首先,你必须设置数组的值......
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
你得到这个是因为int的默认值是0
,这就是为什么显示所有0
..
要获取数组的随机值,请使用Collections.shuffle