javaarraysstringfunction2d

Returning a row of 2D array as comma delimited string given row number


I'm attempted to create a function that will accept the row number of a 2D array as an integer and return a string that contains a comma-delimited list of the values in that row.

This is a block of code below that I've managed to write, but it returns the entire array. I've attempted to look at the syntax for StringBuilder and modify it to no avail. Would someone mind assisting?

public String getRow(int row) {

    for(String[] s1 : this.desks) {
        this.sb.append(Arrays.toString(s1));
        this.oneRow = sb.toString();
       }
     return this.oneRow;

Solution

  • You shouldn't be looping if you want the first row, use index row (after first checking it's a valid index). Like,

    public String getRow(int row) {
        if (row < desks.length) {
            return Arrays.toString(desks[row]);
        }
        return ""; // <-- or null, or throw an exception.
    }