以下代码应该对卡片数组中的卡片进行递归二分搜索。 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==0
、 comp<0
和 comp>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/