有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

       //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;
    }
    

    Here You may try this. You will get Your Answer.

  2. # 2 楼答案

    如果需要具有不同行数的值的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;
        }
    }