Iterate through 2 dimensional array

前端 未结 5 1926
心在旅途
心在旅途 2020-12-10 13:30

I have a \"connect four board\" which I simulate with a 2d array (array[x][y] x=x coordinate, y = y coordinate). I have to use \"System.out.println\", so I have to iterate

5条回答
  •  北海茫月
    2020-12-10 14:21

    Simple idea: get the lenght of the longest row, iterate over each column printing the content of a row if it has elements. The below code might have some off-by-one errors as it was coded in a simple text editor.

      int longestRow = 0;
      for (int i = 0; i < array.length; i++) {
        if (array[i].length > longestRow) {
          longestRow = array[i].length;
        }
      }
    
      for (int j = 0; j < longestRow; j++) {
        for (int i = 0; i < array.length; i++) {
          if(array[i].length > j) {
            System.out.println(array[i][j]);
          }
        }
      }
    

提交回复
热议问题