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;
}
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();
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With