Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Object Null Check for method

I need to create a null check in this formula for the books[i] and I am not entirely sure how to go about this as I am not greatly familiar with null checks and very new at programming. Any and all help is much appreciated!

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

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

    return total;
}
like image 993
CoShark Avatar asked Feb 09 '14 20:02

CoShark


2 Answers

First you should check if books itself isn't null, then simply check whether 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();
   }
}
like image 107
Kuba Spatny Avatar answered Sep 23 '22 07:09

Kuba Spatny


You can add a guard condition to the method to ensure books is not null and then check for null when iterating the array:

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;
}
like image 37
Kevin Bowersox Avatar answered Sep 26 '22 07:09

Kevin Bowersox