2012-02-08 127 views
0

我该如何打印?二维阵列

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

该行ROWS ++;不应该在那里。 – 2012-02-08 12:05:55

+1

您可以编辑您的帖子以将其删除。标签下面有一个“编辑”链接。 – Mat 2012-02-08 12:07:41

+1

由于未在a2数组中填充值,因此您正在归零? – 2012-02-08 12:07:50

回答

3

您需要填充a2如果你希望它包含非零值:

for (int col = 0; col < COLS; col++) { 
    a2[row][col] = row * COLS + col + 1; // <---- added this line 
    output += " " + a2[row][col]; 
} 

此外:

  1. 你缺少一个右大括号。它应该在output += "\n";之后。
  2. ROWS++的用途不明,看起来奇。

另外我想随机打印出数字。我怎样才能做到这一点?

三个简单的步骤:

  1. 填入a2如上;
  2. randomly shufflea2;
  3. 打印出来(你已经知道如何做到这一点)。
+0

很好的答案!不修复整个代码(从作业开始),但指向正确的方向。 – 2012-02-08 18:11:24

0
  1. 使用线,通过上述AIX提出:a2[row][col] = row * COLS + col + 1;
  2. 删除线ROWS++
  3. 对于随机数1D阵列上使用Collections.shuffle,然后组BU行和列
0

以及你阵列是空的

尝试广告I整流器初始化:

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); 
+1

尽量不要在家庭作业时解决所有问题,而应指向正确的方向或提供提示和技巧。 – 2012-02-08 18:12:14

0

要获得与预期相符导致....
首先你必须设置你的阵列的价值.. 。

0 0 0 0 
0 0 0 0 
0 0 0 0 
0 0 0 0 

你得到这一点,因为INT的默认值是0这就是为什么显示所有0。 。
要获得您的阵列的随机值使用Collections.shuffle