简体   繁体   中英

How do you get a data value associated with a specific col,row from a 2-d array in java?

here is the code I have written in java I think it is right. I am just not sure what to set result to? I want to return the element associated with the specific row column

public int getElement(int row,int col){
    int result = 0;
    if(((row>=1) && (row <=rowArray.length))&&((col>=1) && (col <=colArray.length))){
        result = ??
    }
    return result;
}             

Why do you have 2 separate array for making a 2d array ?

Your class content should be like :

public int array2D[10][15]; // 10 row and 15 col

public int getElementAt(int rowIndex, int colIndex)
{
    int ret;
    if( rowIndex >= 0 && rowIndex < array2D.length && colIndex >= 0 && colIndex < array2D[0].length )
    {
        ret = array2D[rowIndex][colIndex];
    }
    else
    {
        // Throw something according to what you want or exit or special return value
    }
    return ret;
}

If you just have one row array and one column array then you have something like this

  foo bar baz
  sna
  fu

but what you really want is something like this

  foo bar baz
  sna rah boo
  fu  man chu

You'd declare this something like:

class MyClass {
  String myArray[][] = new String[3][3];

  MyClass() {
    // assign data into myArray
  }

  String getAt(int i, int j) {
    if ((i >= 0) && (i < myArray.length) &&
        (j >= 0) && (j < myArray[i].length)) {
      return myArray[i][j];
    }
    return null;
  }
}

If you actually have a non-rectangular array, then you will have to check rowArray[row].length instead of colArray.length.

Then you will set result = rowArray[row][col];

But since you did not actually disclose the rowArray declaration and the colArray declaration, we all are just guessing.

First, arrays are indexed from 0 not 1. Typical idiom is something like "if ( row >= 0 && row < rowArray.length ) { ... }".

Also, for such simple expressions you don't need so many parenthesis; it overly complicates the expression. Keep it simple. If you really want to you could group each individual comparison, but I probably wouldn't.

Finally, your code would look like:

public int getElement(int row, int col) {
   int result = 0;
   if ((row >= 0) && (row < rowArray.length) &&
       (col >= 0) && (col < colArray.length)) {
      result = rowArray[row][col];
   }
   return result;
}

Reading your comments, im not sure what exactly you want.
Do you want something like:
List1: ItemA, ItemB, ItemC ...
List2: ItemD ...
List3: ItemE, ItemF ..

if so, i would suggest using an Array (1-dimension) of LinkedLists. That way, the array index represent the row, and the list represent the columns in that row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM