有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于检查数组是否为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


共 (3) 个答案

  1. # 1 楼答案

    尝试先检查null,因为先检查null更安全。对于长度,也可以使用方法isEmpty()

    public static int smallestNumber (int[] array1) {
    
    if (array1 == null) {
        return 0;
    }
    
    if (array1.isEmpty()) {
        return 0;
    }
    
       int smallest = array1[0];
       for (int element : array1) {
          if (element < smallest) {
               smallest = element;
          }
       }
        return smallest;
    }
    

    或者将其添加为alt:

    public static int smallestNumber (int[] array1) {
    
    if (array1 != null) {
        if (array1.isEmpty()) {
            return 0;
        }
    
      int smallest = array1[0];
    
      for (int element : array1) {
          if (element < smallest) {
               smallest = element;
          }
       }
          return smallest;
    
       } else {
         return 0;
        }
    }
    
  2. # 2 楼答案

    public static int smallestNumber (int[] array1) {
        if (array1 == null || array1.length == 0) {
            return 0;
        }
    
        int smallest = array1[0];
        for (int element : array1) {
            if (element < smallest) {
                smallest = element;
            }
        }
    
        return smallest;    
    }
    
  3. # 3 楼答案

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

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

    总之,在尝试访问任何数组值之前,请将赋值移动到else块中的smallest,并检查空数组或空数组的条件

    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;
    }