java checkfornull,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

回答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(); }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值