检查整数值是否为空时出现Java异常

检查整数值是否为空时出现Java异常,java,null,nullpointerexception,integer,Java,Null,Nullpointerexception,Integer,以下代码片段导致我的程序抛出空指针异常,我正在努力确定原因: private void ...(){ HierarchyForm hForm = (HierarchyForm) Integer id = hForm.getId(); if (id != null && id.intValue() > 0){ <-- exception thrown here ... } . . . } priv

以下代码片段导致我的程序抛出空指针异常,我正在努力确定原因:

private void ...(){
    HierarchyForm hForm = (HierarchyForm)
    Integer id = hForm.getId();
    if (id != null && id.intValue() > 0){ <-- exception thrown here
        ...
    }
    .
    .
    .
}
private void…(){
层次形式hForm=(层次形式)
整数id=hForm.getId();

如果(id!=null&&id.intValue()>0){您需要这样写:

private void ...(){
  HierarchyForm hForm = (HierarchyForm)
  Integer id = hForm.getId();
  if (id != null)
     if (id.intValue() > 0){ <-- exception thrown here
     ...
     }
  }
  . 
  .
  .
}
if (id != null & id.intValue() > 0) {
if (id != null && id.intValue() > 0) {
private void…(){
层次形式hForm=(层次形式)
整数id=hForm.getId();
如果(id!=null)

如果(id.intValue()>0){如果id为null,则该行不应抛出NPE

如果&&的第一个操作数为false,则不计算第二个操作数,结果为false


请再次检查您的代码,并确保您在计算id.intValue()时在这一行获得NPE。

使用此格式可以找到正确的解决方案:

String id = request.getParameter("id");

        if(id!=null && !id.toString().equalsIgnoreCase(""))
        {
            user.setId(Integer.parseInt(id));
            dao.updateUser(user);
        }
        else
        {
            dao.addUser(user);
        }
如果使用另一种类型的格式:

String id = request.getParameter("id");

        if(id == null || id.isEmpty())
        {
            dao.addUser(user);
        }
        else
        {
            user.setId(Integer.parseInt(id));
            dao.updateUser(user);
        }
它很简单,放一个空检查!用if语句包围你的对象,比如

Object mayBeNullObj = getTheObjectItMayReturnNull();

if (mayBeNullObj != null) 
   { 
     mayBeNullObj.workOnIt(); // to avoid NullPointerException
   }

但是,它们都给出了相同的结果。

这一行导致NPE的唯一方式是在
null
元素上执行
id.intValue()

如果
id!=null
为false,Java将不会执行
id.intValue()
,因为
&&
缩短了执行过程

我怀疑您的代码实际上是这样的:

private void ...(){
  HierarchyForm hForm = (HierarchyForm)
  Integer id = hForm.getId();
  if (id != null)
     if (id.intValue() > 0){ <-- exception thrown here
     ...
     }
  }
  . 
  .
  .
}
if (id != null & id.intValue() > 0) {
if (id != null && id.intValue() > 0) {
而它应该是这样的:

private void ...(){
  HierarchyForm hForm = (HierarchyForm)
  Integer id = hForm.getId();
  if (id != null)
     if (id.intValue() > 0){ <-- exception thrown here
     ...
     }
  }
  . 
  .
  .
}
if (id != null & id.intValue() > 0) {
if (id != null && id.intValue() > 0) {

是否确实在此行引发异常?这是不可能的。如果
hForm
变量为null,它将在尝试访问
.getId()时引发null指针
变量的方法。@lakshman如果是这种情况,代码不会下降,因为它的计算结果是
if!=null
…请展示一个简短但完整的程序来演示问题。从您发布的内容来看,这似乎不太可能…hform本身不是null。只有hform id值。整数id设置正确。这是我的想法,但我不同意e仅使用“if(id.intValue()>0)”进行测试,但仍然得到exception@pythonicate如果
id
为null,则
If(id.intValue()>0)
抛出NPE是正常的。但是如果您的实际代码是
If(id!=null&&id.intValue()>0)
那是不可能的。没错。这就是为什么我感到困惑的原因,即使id为!=null检查,它也会失败。@pythonicate不能。这是不可能的。@pythonicate看起来你没有执行你看到的代码,或者问题出在其他地方。再次,发布stacktrace。