首页 > 解决方案 > if 语句检查数组是否为空或空,不起作用

问题描述

我的主要任务是工作(粗略翻译):

编写一个方法,该方法返回一维整数数组中的最小数。

现在我必须做一个附带任务(粗略的翻译):

添加 if 语句,检查数组是否为 null 或为空,如果是,则返回 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.length == 0;

标签: java

解决方案


首先,数组的大小为非负数,因此array1.length不能为 -1,而是与 进行比较0

其次,赋值 int smallest = array1[0];尝试访问空数组的第 0 个位置,这将导致java.lang.ArrayIndexOutOfBoundsException.

因此,总而言之,将赋值移到smallestelse 块中,并在尝试访问任何数组值之前检查空数组或空数组的条件。

public static int smallestNumber (int[] array1) {

    int smallest;

    if (array1 == null || array1.length == 0) {
        return 0;
    }

    else {
        smallest = array1[0];
        for (int element : array1) {
            if (element < smallest) {
                smallest = element;
            }
        }
    }
    return smallest;
}

推荐阅读