itSp4x itSp4x - 8 months ago 63
Java Question

Return specific value from a 2D array

I'm trying to figure out a way to return the value from a specific position inside a 2D array in JAVA. I've been searching for hours. I might be tired, or using the wrong terms but I can't find anything useful so far...

So for example I have a variable "a" and I want it to receive the value that is contained at a specific array position.

So for example, I want the value contained at the position :


To be saved into the variable "a". Any way to do this? Btw it's a 9x9 array so it contains 81 different value but I only need 1 specific value out of the array at a time.

Thanks in advance!


You just assign the value from the array as desired:

public class Foo {
    public static void main(String[] args) {
        int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
        int a = arr[1][1];

// outputs : 5

Note that if a value hasn't been put in an array position then it will be in the uninitialized state. For an int this is 0.

int[][] arr = new int[9][9];
// all values in arr will be 0