空指针除外,但为什么呢?

时间:2013-10-09 01:32:10

标签: java eclipse

当我使用这两种方法运行程序时,我得到了一个nullpointerexception:

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()的结果是一个枚举。

1 个答案:

答案 0 :(得分:0)

我认为这一行是错误的:

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 ( );