如何使用for循环创建二维数组并分配增量为10的线性值



我想使用for循环创建一个二维数组,并且我想分配增量为10的值。到目前为止,这就是我所拥有的,但我没有得到我想要的结果。。。

package ~/TwoDimensionalArray;
import java.util.Scanner;
public class TwoDimensionalArray {
public static void main(String[] args) {
int rows = 3;
int columns = 3;
int[][] array = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
array[i][j] = j * 10;
System.out.println(array[i][j]);
}
}
}
}

以下是我想要的输出:

0   30  60
10  40  70
20  50  80
Process finished with exit code 0

以下是我一直得到的:

0
10
20
0
10
20
0
10
20
Process finished with exit code 0
  • 不应在每个数字后面打印新行
  • 只应在打印每一行之后,即在外循环的每次迭代之后,打印一行新行
  • 你还应该在每个数字后面打印一个制表符,这样数字就不会粘在一起了
  • 您应该使用公式j * 10 * rows + i * 10计算第i行第j列的数字。这将为您提供每个位置的正确数字
int rows = 3;
int columns = 3;
int[][] array = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
array[i][j] = j * 10 * rows + i * 10;
System.out.print(array[i][j]); // "print" doesn't print a new line
System.out.print("t"); // print a tab!
}
System.out.println(); // print a new line here
}

也许这就是你想要的

public class TempTest {
static final int ROW = 3;
static final int COLUMN = 3;
public static void main(String[] args) {
int[][] array = new int[ROW][COLUMN];
// assign values to array
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
array[i][j] = 10 * (i + 3 * j);
}
}
// display array
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
System.out.print(array[i][j]);
System.out.print(' ');
}
System.out.println();
}
}
}

结果将是

0 30 60 
10 40 70 
20 50 80 

我想你不熟悉printprintln之间的区别,后者会增加一行。尝试学习更多关于JAVA的知识,祝你好运!

试试这个。

int rows = 3;
int columns = 3;
int[][] array = new int[rows][columns];
for (int i = 0, v = 0; i < rows; i++) {
for (int j = 0; j < columns; j++, v += 10) {
array[i][j] = v;
System.out.print(array[i][j] + "t");
}
System.out.println();
}

最新更新