如何创建一个在java中使用2D数组的方法

时间:2016-04-02 15:21:37

标签: java for-loop multidimensional-array

我想创建一个计算多少次的方法 在2D数组中发生了一个数字。 使用for循环

2 个答案:

答案 0 :(得分:1)

2D数组可以声明为int[][] matrix = new int[10][10];如果您需要行中具有不同数量值的2D数组,那么您必须自己创建每一行:

int [][] matrix = new int[10][];
matrix[0] = new int[10];
matrix[1] = new int[20];
//...

迭代matrix您需要

for (int[] row : matrix) {
    for (int value : row) {
        sum += value;
    }
}

答案 1 :(得分:0)

   //method to count your number of Occurrences in Your 2-D Array.    
private int getAllOccurence(int [] arr, int yourNumberToSearch){ 
 int count = 0;
for (int[] row : arr) {      //loop will able to get all Rows

    for (int value : row) {      //loop enables you to get each values of each Row.

       // This if Statement will check wheather Your Number exists in array or not
        if(value == yourNumberToSearch) 
              count++; //count increase each times by one If Number exists in a array.
    }
  }
  return count;
}
  

在这里你可以试试这个。你会得到答案。