Nikhil Khedekar Nikhil Khedekar - 4 months ago 8
Java Question

Eclipse giving an error about not returning an integer

The following code is supposed to do a recursive binary search for a card in a array of cards. Eclipse gives an error that the method does not return an integer.

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


the compareto method:

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

Answer

Since your if-else-if statements cover all possible values of comp (comp==0, comp<0 and comp>0), you should change the last else if :

else if (comp>0)

to else :

else

This way the compiler will realize that your method always returns a value.

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