java - 二维数组

标签 java arrays random

如何打印此内容?

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];
}

另外:

  1. 您缺少一个右大括号。它应该位于 output += "\n"; 之后。
  2. ROWS++ 的用途尚不清楚,而且看起来非常奇怪。

Also I want to print out the numbers at random. How can I do that?

三个简单步骤:

  1. 如上填充a2
  2. randomly shuffle a2
  3. 将其打印出来(您已经知道如何操作)。

关于java - 二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9192959/

相关文章:

java - Eclipse EXCEPTION_ACCESS_VIOLATION 崩溃

java - SQL 序列 : Hibernate and Liquibase

Javascript 诗歌生成器——将子字符串与数组中的任何单个元素匹配

gcc - Stack Guard 和 Stack Smashing Protection - 金丝雀、内存

java - Android:如何以编程方式从提供的 HTTPS URL 下载 SSL 证书?

java - Apache HTTP 客户端 4.2.5 NTLM 集成身份验证

c - 结构数组操作

javascript - 检查数字是否在数组中的最快方法?

c++ - 来自数组的随机字符串

php - PHP如何获取1~N的随机值但不包括几个特定值?