0

我正在解决给定二维数组的问题。问题是,两个数组中的一个数组可能不存在于给定的二维数组中。二维数组中缺少数组检查 - Java

我想我可以做一个简单的长度检查或空检查,但都没有工作。无论哪种方式,我都会得到一个arrayIndexOutOfBounds异常。

String smartAssigning(String[][] information) { 
int[] employee1 = new int[3]; 
int[] employee2 = new int[3]; 
String name1 = ""; 
String name2 = ""; 

if(information[1].length <= 0 || information[1] == null) 
{ return information[0][0];} 

Caused by: java.lang.ArrayIndexOutOfBoundsException: 1 
at _runefvga.smartAssigning(file.java on line 7) 
... 6 more 

所述第一阵列位于索引0存在,但在索引1处的第二阵列不存在。是否有另一种方法来检查这个?

+3

您应该创建一个Employee类。不要使用这么多的并行数组/变量。 – 4castle

+1

你正在检查'[1]'但是返回'[0]'? – brso05

+2

'(information [1] .length <= 0 || information [1] == null)'?所以它是:首先解引用可能的空指针,然后检查,如果它是'null'? – fabian

回答

1

information.length将返回包含的数组的数量。 information[n].length将返回索引n处的数组长度。当您检查if(information[1].length <= 0 ...时,您正在检查是否有第二个数组以及该数组的长度是多少。如果没有第二个数组,你会得到一个界限。

尝试:

for(String[] array : information) { 
    //do something... 
} 
0

你需要采取在考虑此条件的检查顺序。

您写道:

if(information[1].length <= 0 || information[1] == null) 

所以第一information[1].length <= 0被选中,只有当这是假的比information[1] == null检查。

第二个条件是没有意义的,如果information[1] == null比评估information[1].length时已经有一个Exception抛出。

所以,你需要的顺序切换到:

if(information[1] == null || information[1].length <= 0) 

第二个数组不存在,所以information[1] == null是真的

+0

'information [1] == null'仍然可以抛出IndexOutOfBoundsException,您需要首先检查数组'information!= null'和'information.length'。 –

0

Java中的2维数组实际上就是数组的数组。因此,您需要检查“外部”数组(数组数组)的长度和“内部”数组(您的情况下的int数组)的长度。 不幸的是,从你的代码中不清楚你想要做什么,所以根据你的目标和你对呼叫者的了解(例如信息本身可能为空),你可能需要检查以下的一些或全部内容:

information!=null 
information.length 
information[x]!=null 
information[x].length 
+0

对象信息的类型是String [] []' –

+0

@SusannahPotts哦,是的,谢谢!我纠正了这一点。 –

+0

不客气! –