java - Eclipse 给出关于不返回整数的错误

标签 java arrays recursion binary-search

以下代码应该对卡片数组中的卡片进行递归二分搜索。 Eclipse 给出错误,指出该方法不返回整数。

public static int binaryrSearch(Card[] cards, Card target , int low , int high)
{
    if (high<low)
    {
        return -1;
    }
    int mid = (low+high)/2;
    int comp = cards[mid].compareTo(target);
    if(comp==0)
    {
        return mid;
    }else if(comp<0)
    {
        return binaryrSearch(cards , target , mid+1 , high);
    }else if (comp>0)
    {
        return binaryrSearch(cards , target , low , mid-1);
    }
}

比较方法:

public int compareTo(Card that){
    if(this.suit<that.suit)
    {
        return -1;
    }
    if(this.suit>that.suit)
    {
        return 1;
    }
    if(this.rank<that.rank)
    {
        return -1;
    }
    if(this.rank>that.rank)
    {
        return 1;
    }
    return 0;
}

最佳答案

因为您的 if-else-if 语句涵盖了 comp 的所有可能值( comp==0comp<0comp>0 ),您应该更改最后一个 else if :

else if (comp>0)

其他:

else

这样编译器就会意识到你的方法总是返回一个值。

...
if (comp==0) {
    return mid;
} else if (comp<0) {
    return binaryrSearch(cards , target , mid+1 , high);
} else {
    return binaryrSearch(cards , target , low , mid-1);
}
...

关于java - Eclipse 给出关于不返回整数的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505531/

相关文章:

java - 未在子资源方法上调用 Jersey NameBinding 过滤器

java - 自底向上归并排序的实现中是否存在可能的勘误表

arrays - Delphi如何解析带有指针(无类型)参数的重载函数?

c# - 在 C# 中模拟 CTE 递归

c - 递归列表

java - 编译Simple自定义标签类时出现错误

java - 在Eclipse中设置安全策略文件

javascript - 动态创建javascript数组,其名称在java脚本字符串中

c - 在c中生成随机数并将其存储在数组中

algorithm - 一个简单计数问题的递归算法