0

So I'm given a parameter in which the user chooses which row he wants me to print out, how do I print out the row that the user wants?

This is my 2D array: Jewel[][] myGrid;

 public Jewel[] getRow(int row) { 
     return null; 
 }
6

2 Answers 2

-1

If the first dimension of your Jewel[][] myGrid is the row index:

public Jewel[] getRow(int row) { 
    return myGrid[row]; 
}

If the second dimension in the row index:

public Jewel[] getRow(int row) { 
    Jewel[] result = new Jewel[myGrid.length];
    for (int i = 0; i < myGrid.length; i++) {
        result[i] = myGrid[i][row];
    }
    return result; 
}

Then you simply call

System.out.println(Arrays.toString(getRow(0)));
Sign up to request clarification or add additional context in comments.

Comments

-1

run a for loop to cycle through that row by getting the amount of columns in that row. In each loop, get that number from the 2d array and add it to a list. Return that list. I can write the code for you if you need.

for(int i = 0; i < myGrid[row].length; i++){
    System.out.println(myGrid[row][i]);
}

6 Comments

could you please write the code, it would make it easier for me to understand
@Issa sure. Ill edit it in a minute.
@Issa let me know if this solves the issue.
I hope someone gets to take your code and get credit for it and paid for in the very near future.
@gkgkgkgk Why did you make an ArrayList and add that onto myGrid?
|