user1145909
user1145909

Reputation:

Accessing Arrays via an identifier variable - JAVA

I am trying to access an array based on a number. Let me explain:

stringBuilder.append(array1[i]);

but I have 4 arrays, I would like to access the array like this:

int i;
int aNum;

stringBuilder.append(array(aNum)[i]);

so the array number selected depends on the value of aNum (1 - 4) where [i] being the location of the array (0 - n)

This code however doesn't work. Any ideas? Tried looking on google but can't find the correct code I need. It does seem simple but can't find the solution. Hope it makes sense!

Upvotes: 0

Views: 64

Answers (2)

aliteralmind
aliteralmind

Reputation: 20163

You are referring to a two-dimensional array, which is an array of arrays. Here is an example:

/**
   <P>{@code java TwoDArray}</P>
 **/
public class TwoDArray  {
   public static final void main(String[] ignored)  {
      //Setup
         int[][] intArrArr = new int[4][];
         intArrArr[0] = new int[] {1, 2, 3, 4};
         intArrArr[1] = new int[] {5, 6, 7, 8};
         intArrArr[2] = new int[] {9, 10, 11, 12};
         intArrArr[3] = new int[] {13, 14, 15, 16};
         StringBuilder stringBuilder = new StringBuilder();

      //Go
         int indexOfIntInSelectedArray = 1;   //The second element...
         int indexOfArray = 2;                //...in the third array.

         stringBuilder.append(intArrArr[indexOfArray][indexOfIntInSelectedArray]);

      //Output
         System.out.println("stringBuilder.toString()=" + stringBuilder.toString());
   }
}

Output:

[C:\java_code\]java TwoDArray
stringBuilder.toString()=10

Arrays can contain theoretically contain any number of dimensions:

Upvotes: 2

deanosaur
deanosaur

Reputation: 611

Your array is a two dimensional array (array of arrays). You need to index using two pairs of brackets:

int rows = 4; 
int cols = 5;
int[][] myArray = new int[rows][cols];
int row;
int col;

stringBuilder.append(myArray[row][col]);

Upvotes: 1

Related Questions