[java] The following code won't compile because...

Started by
1 comment, last by Kevinator 15 years, 9 months ago
"This method must return a result of type int Possible problem: the if-statement structure may theoretically allow a run to reach the end of the method without calling return. Consider using a final else {... to ensure that return is always called." My question is... why? My code must return an int as far as I can tell.
private int getNumber(String str, int index) {
  String estr=""+str.charAt(index);
  if(!Character.isDigit(str.charAt(index)))
    return -1;
  else {
    index++;
    while(index<str.length()&&Character.isDigit(str.charAt(index))) {
      estr+=str.charAt(index);
      index++;
    }
    return Integer.parseInt(estr);
  }
}

The following variation results in the same problem:
private int getNumber(String str, int index) {
  String estr=""+str.charAt(index);
  if(!Character.isDigit(str.charAt(index)))
    return -1;
  else {
    index++;
    while(index&lt;str.length()&&Character.isDigit(str.charAt(index))) {
      estr+=str.charAt(index);
      index++;
    }
    return -50;
  }
  return -100;
}


Advertisement
I tried compiling both of the snippets. The first one compiled fine. The second one had an error because "return -100;" is an unreachable statement.
Thanks, this confirms my suspicion that there is something wrong with my compile process rather than my code.

This topic is closed to new replies.

Advertisement