可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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
回答1:
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
回答2:
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
回答3:
If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]); - to check if the parameter is null. To check if each element is not null just use if(null != books[i]){/*do stuff*/}
Example: public static double calculateInventoryTotal(Book[] books){ Objects.requireNotNull(books, "Books must not be null"); double total = 0; for (int i = 0; i
回答4:
You simply compare your object to null using the == (or !=) operator. E.g.: 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
回答5:
If array of Books is null, return zero as it looks that method count total price of all Books provided - if no Book is provided, zero is correct value: public static double calculateInventoryTotal(Book[] books) { if(books == null) return 0; double total = 0; for (int i = 0; i
It's upon to you to decide if it's correct that you can input null input value (shoul not be correct, but...).
回答6:
Inside your for-loop, just add the following line: if(books[i] != null) { total += books[i].getPrice(); }