Eclipse给出了一个关于不返回整数的错误

时间:2016-07-21 13:24:50

标签: 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);
    }
}

compareto方法:

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;
}

4 个答案:

答案 0 :(得分:4)

由于您的if-else-if语句涵盖了compcomp==0comp<0comp>0)的所有可能值,因此您应该在以下情况下更改最后一个:< / p>

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);
}
...

答案 1 :(得分:2)

尝试在binaryrSearch方法

的末尾添加return语句
public static int binaryrSearch(Card[] cards, Card target , int low , int high)
{
   ....
   ....
   return 0;
}

答案 2 :(得分:0)

您必须在方法的末尾添加一个return语句:

    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);
    }
   return 0;
}

答案 3 :(得分:0)

这两种方法,添加一个永远不会达到的return语句,并删除最后一个if if working。谢谢你们的帮助。