[英]NullPointerException occuring after null check java
I have this if statement 我有这个if语句
if((check1==null||!check1.isSolid())&&(check2==null)||!check2.isSolid())
it throws a null pointer exception because check1 or check2 are null, but i don't understand why it is doing this, because i am checking for the null condition before i am accessing the object and if the object is null why would java bother checking isSolid because it would have already been true. 它抛出一个空指针异常,因为check1或check2为null,但是我不明白为什么这样做,因为我在访问该对象之前正在检查null条件,并且如果该对象为null为什么Java会麻烦检查isSolid,因为它本来应该是真实的。
Your messed up your parenthesis. 您搞砸了您的括号。 Java will group your statement together like this:
Java会将您的语句组合在一起,如下所示:
((check1 == null || !check1.isSolid()) && check2 == null) || !check2.isSolid()
If check1
is null
and check2
, is null
, the first statement will evaluate to true
. 如果
check1
为null
而check2
为null
,则第一条语句的值为true
。 The problem occurs when your move on to the second statement, since check2
is null
, check2.isSolid()
will through a NullPointerException
. 当您移至第二条语句时会发生问题,因为
check2
为null
, check2.isSolid()
将通过NullPointerException
。
Change your parenthesis to 将您的括号更改为
(check1 == null || !check1.isSolid()) && (check2 == null || !check2.isSolid())
You mixed up the parentheses. 您弄混了括号。 Try:
尝试:
if((check1==null||!check1.isSolid())&&(check2==null||!check2.isSolid()))
Try this: 尝试这个:
boolean check1_result = (check1 == null) ? true : !check1.isSolid();
boolean check2_result = (check2 == null) ? true : !check2.isSolid();
if (check1_result && check2_result)
// do work...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.