你怎么样检查一个值是否在二维数组的特定位置?

huangapple go评论108阅读模式
英文:

How can I check if a value is in a certain place of a 2D array?

问题

我正在创建一个二维数组:
int[][] family = new int[10][];
然后我通过family[0][0] = 2将数字2添加进去。

如何检查数组的第一个元素中是否有值2?

我尝试过if (family[0][0] == 2){return true;},但当我运行程序时,它直接跳过这部分。

完整代码:

        int[][] family = new int[1000000][];
		Random rn = new Random();
		Family f = new Family();
		
		int answer = rn.nextInt(2) + 1;

		try {
			family[0][0] = answer;
		

		if (family[0][0] == 1) {
			System.out.println();
		}
			
		
		} catch (NullPointerException npe) {}```


<details>
<summary>英文:</summary>

I&#39;m creating a 2D Array:
```int[][] family = new int[10][];```
and I then add the number two to it with ```family[0][0] = 2```

How do I check if the value 2 is in the first element of the array or not?

I&#39;ve tried ```if (family[0][0] == 2){return true;}``` but when I run the program it just skips over it.

Full code:
    int[][] family = new int[1000000][];
	Random rn = new Random();
	Family f = new Family();
	
	int answer = rn.nextInt(2) + 1;

	try {
		family[0][0] = answer;
	

	if (family[0][0] == 1) {
		System.out.println();
	}
		
	
	} catch (NullPointerException npe) {}```

答案1

得分: 0

你在二维数组初始化时没有声明列的长度,或者在赋值给family[0][0]之前没有声明列的长度,因此你可以像这样做:int[][] family = new int[2][2];,这样就会有一个包含2行2列的数组,或者你可以为每一行(比如第0行)创建动态数量的列,使用family[0] = new int[2];

动态方法在以下代码中显示:

public class StackOverflow
{
    public static void main(String[] args)
    {
        int[][] family = new int[10][0]; 
        family[0] = new int[2]; //初始化第0行,有2列
        family[0][0] = 2; //在位置[0,0]处向family数组添加2
        System.out.println(check(family));
    }
    
    static boolean check (int[][] family)
    {
        if (family[0][0] == 2)
        return true;
        else return false;
    }
}
英文:

You haven't declared length of column during 2D array initialization or before assigning value to family[0][0], so either you can do it like int[][] family = new int[2][2]; thus having an array of 2 rows and 2 columns or you can create dynamic number of columns for each row(say row 0) using family[0] = new int[2];.

The dynamic approach is shown in the code below:

public class StackOverflow
{
    public static void main(String[] args)
    {
        int[][] family = new int[10][0]; 
        family[0] = new int[2]; //Initializing Row 0 with 2 Columns
        family[0][0] = 2; //Adding 2 to family array at position [0,0]
        System.out.println(check(family));
    }
    
    static boolean check (int[][] family)
    {
        if (family[0][0] == 2)
        return true;
        else return false;
    }
}

huangapple
  • 本文由 发表于 2020年8月28日 12:08:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63627317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定