【问题标题】:Null Pointer Except, but why? [closed]空指针 除了,但为什么? [关闭]
【发布时间】:2013-10-09 01:32:09
【问题描述】:

当我使用这两种方法运行我的程序时,我得到了一个空指针异常:

public static String getType(int x)
{
    Contact_Type Type;
    String strType = "";

    Type = AddyBook.get(x).getContactType();
    strType = Type.toString ( );
    return strType;
}

public static String displayByType(String type)
{
    int i = 0;
    String strTypeList = "";

    if(type.equals(null))
        strTypeList = "What?What?What?LOLOLOLOLOLnopechucktesta";
    while(i < AddyBook.size())
    {
        if(getType(i).equalsIgnoreCase(type))
        {
            strTypeList += getType(i);
            strTypeList += "\n";
        }
        i++;
    }
    return strTypeList;
}

我被指向的行是

strType = Type.toString ( );

if(getType(i).equalsIgnoreCase(type))

除了它们正在操作的变量之外,我还在其他相同的方法中遇到异常。

我的问题是,在我的驱动程序类中,我直接测试了“getType”方法,它工作正常。然后,在“displayByType”方法中,我什至说“如果 Type 为 null,请执行此操作”,但它仍然只是抛出异常。我不知道为什么,但我觉得这可能非常简单明了;我一直在研究这个太久了,现在看不到它。 :/

编辑1:Type = AddyBook.get(x)的内容是一个对象,.getContactType()的结果是一个枚举。

【问题讨论】:

  • 类型为空。现在回头看看这里,AddyBook.get(x).getContactType(); 看看为什么。
  • 你在哪里填充你的 AddyBook - 它不起作用
  • 我认为这不是问题所在。就像我说的那样,我直接测试了该方法并且它可以正常工作。我在另一个类中填充它,它工作正常。
  • @Riqqu:那么你的测试很糟糕,非常糟糕。在找到错误的根源之前不要做任何假设。我可以向您保证,AddyBook.get(x).getContactType(); 正在为您在调用该方法时使用的某个变量 x 返回 null。保证。
  • 这个"Edit 1: The contents of Type = AddyBook.get(x) is an object, and the result of .getContactType() is an enumeration." 什么也没告诉我们。没有代码,我们无法做出任何假设。显示代码。

标签: java eclipse


【解决方案1】:

我认为这条线是错误的:

if(type.equals(null))
    strTypeList = "What?What?What?LOLOLOLOLOLnopechucktesta";

应该是:

if(type == null)
    strTypeList = "What?What?What?LOLOLOLOLOLnopechucktesta";

这里没有看到方法调用的内容:

Type = AddyBook.get(x).getContactType();

这将很难调试,但如果我猜测它会是方法“getContactType()”返回 null。

编辑:

尝试解开调用:

代替:

Type = AddyBook.get(x).getContactType();
strType = Type.toString ( );

试试:

Entry entry; // I don't actually know what .get() returns
entry = AddyBook.get(x);
if (entry == null)
    throw new RuntimeException("entry is null at "+x+" book size="+AddyBook.size());

Type type = entry.getContactType();
if (type == null)
    throw new RuntimeException("type is null from entry="+entry.toString());

strType = Type.toString ( );

【讨论】:

  • 根据他的错误信息,我认为这不是问题。
  • 另外,查看文档,.equals(null) 应该返回 false,而不是抛出 NPE。
  • @DennisMeng: foo.equals(null) 如果调用该方法的变量(此处为 foo)为空,则会抛出 NPE。所以贾斯汀,你的观点是好的,但不是他表现出的例外的原因,我不相信。
  • @Riqqu:那么你的测试就被关闭了,因为方法错误。
  • @HovercraftFullOfEels 好吧。我只是指出,如果只有 argument 为空,它不会抛出 NPE。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
  • 2011-05-19
相关资源
最近更新 更多