If 语句中的空指针异常

发布于 2024-12-29 22:15:59 字数 606 浏览 2 评论 0原文

希望你们能够弄清楚为什么我会收到一个空指针异常,该程序有几个类和方法,但这是一个正在破坏的类和方法。

public void search(Node node, String sData, int iData)
{
    if (sData.equals(node.getString()) && (iData == node.getInt()))
    {
        System.out.println("Nailed it");
    }else if (sData.compareTo(node.stringData) < 0)
    {
        search(node.left, sData, iData);
    }else if (sData.compareTo(node.stringData) > 0)
    {
        search(node.right, sData, iData);
    }

}

首先获取输入的节点是根节点,然后它通过递归从那里向左或向右移动,但表明其错误的行是顶部的 if 语句。无法弄清楚出了什么问题 sData 只是调用该方法时的标准字符串输入,而 iData 也只是一个 int 输入。无法弄清楚=/感谢您的帮助

Hoping you guys can figure out why im getting a null pointer exception with what I can provide, the program has several classes and method but this is the one that is breaking.

public void search(Node node, String sData, int iData)
{
    if (sData.equals(node.getString()) && (iData == node.getInt()))
    {
        System.out.println("Nailed it");
    }else if (sData.compareTo(node.stringData) < 0)
    {
        search(node.left, sData, iData);
    }else if (sData.compareTo(node.stringData) > 0)
    {
        search(node.right, sData, iData);
    }

}

the Node that is getting input at first is the root and then it goes left or right from there through recursion, but the line that says its erroring is the if statement up top. Cannot figure out what is wrong sData is just a standard string input when the method is called and iData is just an int thats input as well. Cannot figure it out =/ thanks for any help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧梦荧光笔 2025-01-05 22:15:59

您需要在方法的顶部添加以下内容:

if (node == null) return;

如果您搜索结构中不存在的内容,这将确保该方法正常返回。否则,对于现有代码,当该方法遇到叶节点时,您将遇到 NullPointerExceptions。

You need to add the following at the top of your method:

if (node == null) return;

This would ensure that the method returns gracefully if you search for something that doesn't exist in the structure. Otherwise with your existing code, you'll encounter NullPointerExceptions when the method encounters leaf nodes.

归属感 2025-01-05 22:15:59

两种可能:sData 或节点为 null;您的递归调用可能会传递空节点,这就是我开始的地方。抱歉,我无法从您的代码中了解更多信息。

此外,如果找不到错误,请考虑使用调试器单步调试代码。这通常有助于编写这样的代码。

Two possibilities: either sData or node are null; your recursive calls potentially pass null nodes, that's what I'd start with. I can't really tell more from your code, sorry.

Additionally, consider using a debugger to step through your code if you can't find the error. That usually helps with code like this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文