user866190
user866190

Reputation: 863

How To Assign A Value To The First Index In a Multi Dimensional Array In Java

I have a 2d array and I want to know how do you set the first value so if my array was

int array[a][b] = int[10][10];

How would you access index 'a' in a for loop?

This is my simple code that I am working on thanks in advance

int[][] timesTable = new int[12][12];

for(int i = 0; i < timesTable.length; i++){
    timesTable[i][i] = i + 1;//can't set the first index with this value
    System.out.println(timesTable[i]);
}

Upvotes: 0

Views: 2327

Answers (2)

Mechkov
Mechkov

Reputation: 4324

I hope you are not putting the "a" and "b" in the array declaration.

int array[][] = int[10][10];

A 2D array is array of arrays. The index "a" or what you are trying to set is another array.

 timesTable[i][i] = i + 1;//can't set the first index with this value

The above can be written like this:

timesTable[i] = {1,2,3};// puts another array at index i

Upvotes: 3

Nate W.
Nate W.

Reputation: 9249

You access your array using [], which you'll need to do n times for an n-dimensional array if you're trying to access a particular element.

If you're simply trying to set the first element, then you can do:

array[0][0] = 100; // some number

If you want to iterate over each element in the entire 2d array, you'll need 2 loops, one for each dimension, like so:

for ( int i = 0; i < array.length; ++i ) {
    for ( int j = 0; j < array[i].length; ++j ) {
        array[i][j] = i + j; // or whatever you want to set the elements to
        System.out.println( array[i][j] );
    }
}

Upvotes: 3

Related Questions