0

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 :

array[1][1]

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!

7
  • 1
    what type of array is this? assuming int array... int a = array[1][1] if you have a already declared just do.. a = array[1][1] Commented Aug 6, 2016 at 21:51
  • When I do this, the variable a always gets the value 0... but yes it is an INT array Commented Aug 6, 2016 at 21:53
  • Would you like to loop through every element in the array?... You're question is confusing and the added comment makes me more confused.. Commented Aug 6, 2016 at 21:54
  • @itSp4x If it's 0 then that's because that's what the value is. Can you show what you're trying to do? Commented Aug 6, 2016 at 21:56
  • 1
    @itSp4x how is the array initialized? Please post your code. Commented Aug 6, 2016 at 21:56

2 Answers 2

1

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];
        System.out.println(a);
    }
}

// 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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this does exactly what I needed!
0

Depending on the "Object type" you would assign using Object a = array[1][1]; and you can be more specific, as in int a = array[1][1];. GL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.