user10509686 :
I have the following chunk of code:
public static boolean isReverse (String s1, String s2) {
if((s1.length()==1)&&s2.length()==1) {
if(s1.equals(s2)) {
return true;
}
}
else if(s1.charAt(0)==s2.charAt(s2.length()-1)) {
return isReverse(s1.substring(1, s1.length()-1),s2.substring(0, s2.length()-2));
}
else return false;
}
I understand that normally you need a return statement to cover the possibility of none of the if statements being true. That is why I have the else return false
at the end, but I still get the error "must return a result of type boolean". Here is the call that I am using it from:
public static void main(String[] args) {
if(isReverse("Java", "avaJ")) {
System.out.println("worked");
}
}
GBlodgett :
In the first if
there is a possibility that there will not be a return statement:
if((s1.length()==1)&&s2.length()==1) {
//What if this is not true?
if(s1.equals(s2)) {
return true;
}
}
In this block if s1
does not equal s2
then it will step out of the if
and since the last return false;
is linked to the else
block, it will reach the end of the method with nothing to return.
To fix this instead of else return false
, simply return false;