用java 二维数组输出下列形式: 1 2 4 7 3 5 8 6 9 10

2024-10-30 07:15:14
推荐回答(2个)
回答(1):

System.out.println("请输入矩阵大小(矩阵的行数):");
Scanner in = new Scanner(System.in);
int row = in.nextInt();
for (int i = 1; i <= row; ++i) {
int j = 1;
for (; j < i; ++j) {
System.out.print(" ");
}
for (; j <= row; ++j) {
System.out.printf("%-6d", ((j - 1) * j / 2 + i));
}
System.out.println();
}

回答(2):

public class Test1 {
public static void main(String[] args) {
int[][] array = new int[4][4];
int index = 1;
for (int col = 0; col < 4; col++) {
for (int row = 0; row <= col; row++) {
array[row][col] = index++;
}
}
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
if (array[row][col] == 0) {
System.out.print("\t");
} else {
System.out.print(array[row][col] + "\t");
}
}
System.out.println();
}
}
}