当前正在尝试打印具有以下输出的矩阵:
0 0 0 0 4
0 0 0 3 0
0 0 2 0 0
0 1 0 0 0
0 0 0 0 0
这是我的当前代码:
for(int row=0; row < matrix.length; row++)
for(int col = 0; col < matrix[row].length; col++)
if(row+col == matrix[row].length)
显然不完整。我什至不确定代码背后的逻辑是否正确。
这是应该起作用的代码(假设矩阵始终为正方形):
for(int row=0; row < matrix.length; row++){
for(int col = 0; col < matrix[row].length; col++){
if(row + col == matrix.length - 1){
matrix[row][col] = col;
System.out.print(col+ " "); // Print value
} else {
matrix[row][col] = 0; // Set value
System.out.print("0 ");
}
}
System.out.println("");
}
我们在条件中减去了1,因为length-1给了我们最后一个索引。 (提醒索引从0开始到长度为-1)
假设总是正方形矩阵。这应该构造您的矩阵。
for(int row=0; row < matrix.length; row++)
{
//System.out.println("");
for(int col = 0; col < matrix.length; col++)
{
//eg [0][4] = 4 on valid condition [5-0-1] == 4
if(matrix.length-row-1 == col)
{
matrix[row][col] = col;
}
//System.out.print(matrix[row][col]);
}
}
对于同一步骤中的打印,只需删除打印注释
注意,int
数组中的默认值为0
,因为int
变量的默认值为0
。因此,您只需要更改所需对角线中的值,并保留其余值即可。
执行以下操作:
public class Main {
public static void main(String[] args) {
final int SIZE = 5;
int[][] matrix = new int[SIZE][SIZE];
// Initialise the matrix
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
if (row + col == matrix.length - 1) {
matrix[row][col] = col;
}
}
}
// Print the matrix
for (int row[] : matrix) {
for (int col : row) {
System.out.print(col + " ");
}
System.out.println();
}
}
}
输出:
0 0 0 0 4
0 0 0 3 0
0 0 2 0 0
0 1 0 0 0
0 0 0 0 0
我已经使用了增强的for循环来打印矩阵。您可以根据需要编写以下内容:
// Print the matrix
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
如有任何疑问,请随时发表评论。