简体   繁体   English

从2D数组返回特定​​值

[英]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. 我试图找出一种从JAVA中2D数组内的特定位置返回值的方法。 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. 因此,例如,我有一个变量“ a”,并且希望它接收包含在特定数组位置的值。

So for example, I want the value contained at the position : 因此,例如,我想要包含在position处的值:

array[1][1]

To be saved into the variable "a". 要保存到变量“ 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. 顺便说一句,这是一个9x9的数组,因此它包含81个不同的值,但是我一次只需要1个特定值即可。

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];
        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,该值为0。

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

Depending on the "Object type" you would assign using Object a = array[1][1]; 根据“对象类型”,您可以使用Object a = array[1][1]; and you can be more specific, as in int a = array[1][1]; 并且您可以更具体一些,例如int a = array[1][1]; . GL GL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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