I have these two methods and Java can’t find the “return” in getNumEmails(). All of them are in the same class, which only has static methods
private static int posSymbol=0;
private static int cont=0;
private static String text=null;
private static int getPosSymbol(){
posSymbol=text.indexOf('@',posSymbol);//if there is no symbol, returns -1
return posSymbol;
}
//Main calls this method
public static int getNumEmails(String completeText){
text=completeText;
while(posSymbol!=(-1)){
posSymbol=getPosSymbol();
if(posSymbol!=(-1)){
cont++;
posSymbol++;
}//close if
else{
return cont; //It seems that it doesn't reach the return always
}//close else
}//close while
}//close method
I know that the solution is simple, to delete the “else” and put the return cont; after the while. But I want to know why Java thinks that getNumEmails() could end without returning anything.
I suppose this is about the compiler complaining
This method must return a result of type int.While compilers can sometimes determine if a function will reach the return statement, this is not always the case. It is mathematically impossible to statically determine the dynamic behaviour of a program.
This is called the “Halting Problem” in computer science; it is impossible to determine, in the general case if a program will or will not terminate.
So even though you can determine that the method will always reach one of your
returnstatements, the compiler may not be able to do so.