如何从返回值的函数中不返回任何内容? [英] How to return nothing from a function that returning value?

查看:398
本文介绍了如何从返回值的函数中不返回任何内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二叉搜索树,我想删除一个节点.

I have a binary search tree, and I want to delete a node.

我需要得到它的父母,所以我写了一个函数:

I need to get its parent, so I wrote a function:

private BSTreeNode<T> getParent(BSTreeNode<T> root, BSTreeNode<T> node) {
        if(root == null) 
            return null;
        if(node.element().lessThan(root.element())) {
            if(root.getLeft() != null && root.getLeft().element().equal(node.element())) 
                return root;
            else
                getParent(root.getLeft(), node);
        } else {
            if(root.getRight() != null && root.getRight().element().equal(node.element()))
                return root;
            else
                getParent(root.getRight(), node);
        }
    }

与C/C ++不同,Java给我以下错误:

Unlike C/C++, Java is giving me the following error:

This method must return a result of type BSTreeNode<T>

它迫使我在函数的最后一行返回一个值.

It forces me to return a value in the last line of the function.

如何在我的功能范围内对其进行修复?

How can I fix it in the context of my function?

推荐答案

您的函数没有针对每种可能的情况返回.你有:

Your function does not have a return for every possible circumstance. You have:

if (null)...

if (less than root)...
else ( if ...)
       else (no return!)

如果它不为null,然后返回最后的其他内容,您将返回什么?什么也没返回.

What do you return if it is not null, and goes to the final else? Nothing is returned.

您可以在else语句中选择return getParent....或return null在函数末尾(不在if或else语句中)

You can either return getParent... in the else statement. or return null at the end of the function (not in an if or else statement)

我经常看到这样的代码来覆盖if语句都不返回值的事件.

I often see code like so to cover the event of neither if statement returning a value.

public int getAnswer()
{
    if (answer.equals("yes"))
        return 0;
    else if (answer.equals("no"))
        return 1;

    return null;
}

这篇关于如何从返回值的函数中不返回任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆