-1

I'm trying to figure out how to display each number from the same "row" of a multi-dimenional array on a sigle line, with a comma to seperate them.

This is how I've declared the multi-dimensional array

int[][] grid = {
            {1, 2, 3},
            {4},
            {5, 6},
            {123, 4567, 78901, 234567}
    };

This is the loop I use to display each "row" on a separate line with the comma's between them:

for(int[] row: grid){
        for(int col: row){
            System.out.print(col + ", ");
        }
        System.out.println();
    }

Alternatively:

for(int row = 0; row < grid.length; row++){
        for(int col = 0; col < grid[row].length; col++){
            System.out.print(grid[row][col] + ", ");
        }
        System.out.println();
    }

It all works fine, but the last number from each "row" gets the comma as well, result:

1, 2, 3, 
4, 
5, 6, 
123, 4567, 78901, 234567,

How can I make it so that the last number does not get a comma?

Nico V
  • 107
  • 1
  • 9

1 Answers1

1

Quite simply, and easily, you can do:

for(String s : Arrays.deepToString(grid).split("(?<=]), "))
{
    System.out.println(s.replaceAll("[\\]\\[]",""));
}

Here:

  • Arrays.deepToString will return the array as a String.
  • .split("(?<=]), ") will split it where the 1-d arrays (in the grid) end.
  • s.replaceAll("[\\]\\[]","") will remove all the [ and ], which are present in the String returned by Arrays.deepToString
dryairship
  • 6,022
  • 4
  • 28
  • 54