Iterate through 2 dimensional array

前端 未结 5 1908
心在旅途
心在旅途 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 13:56
     //This is The easiest I can Imagine . 
     // You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns 
    for(int rows=0;rows<array.length;rows++){
        for(int columns=0;columns <array[rows].length;columns++){
            System.out.print(array[rows][columns] + "\t" );}
        System.out.println();}
    
    0 讨论(0)
  • 2020-12-10 13:58

    Just change the indexes. i and j....in the loop, plus if you're dealing with Strings you have to use concat and initialize the variable to an empty Strong otherwise you'll get an exception.

    String string="";
    for (int i = 0; i<array.length; i++){
        for (int j = 0; j<array[i].length; j++){
            string = string.concat(array[j][i]);
        } 
    }
    System.out.println(string)
    
    0 讨论(0)
  • 2020-12-10 14:05

    Just invert the indexes' order like this:

    for (int j = 0; j<array[0].length; j++){
         for (int i = 0; i<array.length; i++){
    

    because all rows has same amount of columns you can use this condition j < array[0].lengt in first for condition due to the fact you are iterating over a matrix

    0 讨论(0)
  • 2020-12-10 14:09

    Consider it as an array of arrays and this will work for sure.

    int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
                    {15, 25, 35, 45},
                    {27, 29, 37, 48},
                    {32, 33, 39, 50, 51, 89},
                  };
    
    
        for(int i=0; i<mat.length; i++) {
            for(int j=0; j<mat[i].length; j++) {
                System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
            }
        }
    
    0 讨论(0)
  • 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]);
          }
        }
      }
    
    0 讨论(0)
提交回复
热议问题