有 Java 编程相关的问题?

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

方法的Java对象空检查

我需要在这个公式中为书[I]创建一个空检查,我不完全确定如何进行,因为我对空检查不太熟悉,而且编程非常新。非常感谢您的任何帮助

public static double calculateInventoryTotal(Book[] books)
{
    double total = 0;

    for (int i = 0; i < books.length; i++)
    {
        total += books[i].getPrice();
    }

    return total;
}

共 (6) 个答案

  1. # 1 楼答案

    如果书籍数组为空,则返回零,因为该方法计算提供的所有书籍的总价——如果未提供任何书籍,则零是正确的值:

    public static double calculateInventoryTotal(Book[] books)
    {
    if(books == null) return 0;
        double total = 0;
        for (int i = 0; i < books.length; i++)
        {
            total += books[i].getPrice();
        }
        return total;
    }
    

    由您决定是否可以输入空输入值(不应该是正确的,但是…)

  2. # 2 楼答案

    首先,您应该检查books本身是否为空,然后只需检查books[i] != null

    if(books==null) throw new IllegalArgumentException();
    
    for (int i = 0; i < books.length; i++){
       if(books[i] != null){
            total += books[i].getPrice();
       }
    }
    
  3. # 3 楼答案

    如果您使用的是Java 7,那么可以使用Objects.requireNotNull(object[, optionalMessage]);-来检查参数是否为null。要检查每个元素是否不是null,只需使用

    if(null != books[i]){/*do stuff*/}
    

    例如:

    public static double calculateInventoryTotal(Book[] books){
        Objects.requireNotNull(books, "Books must not be null");
    
        double total = 0;
    
        for (int i = 0; i < books.length; i++){
            if(null != book[i]){
                total += books[i].getPrice();
            }
        }
    
        return total;
    }
    
  4. # 4 楼答案

    只需使用==(或!=)操作符将对象与null进行比较。例如:

    public static double calculateInventoryTotal(Book[] books) {
        // First null check - the entire array
        if (books == null) {
            return 0;
        }
    
        double total = 0;
    
        for (int i = 0; i < books.length; i++) {
            // second null check - each individual element
            if (books[i] != null) {
                total += books[i].getPrice();
            }
        }
    
        return total;
    }
    
  5. # 5 楼答案

    在for循环中,只需添加以下行:

    if(books[i] != null) {
         total += books[i].getPrice();
    }
    
  6. # 6 楼答案

    您可以向该方法添加保护条件,以确保books不为null,然后在迭代数组时检查null:

    public static double calculateInventoryTotal(Book[] books)
    {
        if(books == null){
            throw new IllegalArgumentException("Books cannot be null");
        }
    
        double total = 0;
    
        for (int i = 0; i < books.length; i++)
        {
            if(books[i] != null){
                total += books[i].getPrice();
            }
        }
    
        return total;
    }