用于检查数组是否为null或空的java If语句不起作用
我的主要任务是工作(粗略翻译):
Write a method, which returns the smallest number from a 1d array of integers.
现在我必须做一项附带任务(粗略翻译):
Add an if statement to check if the array is null or empty, and if it is, return 0.
方法:
public static int smallestNumber (int[] array1) {
int smallest = array1[0];
if (array1 == null || array1.length == -1) {
return 0;
}
else {
for (int element : array1) {
if (element < smallest) {
smallest = element;
}
}
}
return smallest;
}
主要内容:
public static void main(String[] args) {
int[] tab1 = {}; //empty array?
int smallestNumber = smallestNumber(tab1);
System.out.printf("The smallest number is: %d", smallestNumber);
}
如果我只检查null,则该方法有效。但我不明白为什么它不能在空数组上工作
int[] tab1 = {};
编辑:我也试过array1。长度==0
# 1 楼答案
尝试先检查null,因为先检查null更安全。对于长度,也可以使用方法isEmpty()
或者将其添加为alt:
# 2 楼答案
# 3 楼答案
首先,数组的大小是非负的,因此
array1.length
不能是-1,而是与0
进行比较其次,赋值
int smallest = array1[0];
尝试访问空数组的第0个位置,这将导致java.lang.ArrayIndexOutOfBoundsException
总之,在尝试访问任何数组值之前,请将赋值移动到else块中的
smallest
,并检查空数组或空数组的条件