如何填充二维数组

时间:2020-03-13 16:16:59

标签: java multidimensional-array

好吧,所以我是2D数组的新手,我试图填充尺寸为3x5的2d数组。我要使数字1-15填充数组,并且如果尺寸发生变化(如6x7),则用数字1-42填充它。任何帮助,将不胜感激。对于填充,我需要一个嵌套的for循环并打印出来,我需要为每个循环使用一个嵌套。

3 个答案:

答案 0 :(得分:1)

像这样?

int numRows = 3;
int numCols = 5;    

int[][] arr = new int[numRows][numCols];
int counter = 1;

for (int row = 0; row < numRows; row++) {
    for (int col = 0; col < numCols; col++) {
        arr[row][col] = counter;
        counter++;
    }
}

答案 1 :(得分:1)

类似的事情可以解决问题。

 int nRow = 3;
 int nCol = 5;
 int [][] myArr = new int [nRow][nCol]; //Can replace this with input from user.

  int counter = 1; //Our counter
  for(int i = 0; i < nRow; i++){ //ROW
      for(int j = 0; j < nCol; j++){ //COL
          myArr[i][j] = counter;
          counter = counter + 1;
      }
  }

输出->

 1,2,3,4,5,
 6,7,8,9,10,
 11,12,13,14,15

答案 2 :(得分:1)

我们可以生成如下所示的矩阵

private static int[][] createMatrix(int row , int column){
    int[][] matrix = new int[row][column];
    int value = 1;
    for(int i = 0 ; i < row ; i++){
        for(int j = 0 ; j < column ; j++){
            matrix[i][j] = value++;
        }
    }
    return matrix;
}

用于快速测试的解决方案课程

public class Solution {

 public static void main(String[] args) {
    int[][] matrix = createMatrix(3, 5);
    printMatrix(matrix);
 }

 private static int[][] createMatrix(int row, int column) {
    int[][] matrix = new int[row][column];
    int value = 1;
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < column; j++) {
            matrix[i][j] = value++;
        }
    }
    return matrix;
 }

 private static void printMatrix(int[][] matrix) {

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            System.out.print(matrix[i][j] + " ");
        }
        System.out.println();
    }

  }

}