Skip to main content
GameDev.net gamedev.net
🔒 Locked

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

Started by Kevinator Jul 7, 2008 at 5:28 PM 1 replies 2k views
Original Post
Kevinator
Kevinator
"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<str.length()&&Character.isDigit(str.charAt(index))) {
      estr+=str.charAt(index);
      index++;
    }
    return -50;
  }
  return -100;
}


pinacolada
pinacolada
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.
Kevinator
Kevinator
Thanks, this confirms my suspicion that there is something wrong with my compile process rather than my code.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.