AkshaiShah
AkshaiShah

Reputation: 5939

Missing return statement method

I have the following method:

public int getValue()
{
  if (currentState == COUNTING)
  {
    for (int i = 0; i < 99; i++)
    {
      value = i;
      return value;
    }

  }
  else
    return super.getValue();   
}

I am getting the following error: Missing return statement.

the purpose of the method is if the state is the counting state, the value should increment from 0 to 99, and return the value after each incrementation. If the state is not the counting state, it should use the getValue method from the superclass.

Upvotes: 2

Views: 5099

Answers (3)

shift66
shift66

Reputation: 11958

Compiler can't know is i<99 condition always true or no. If no, in case when currentState == COUNTING method won't return anything. That's why you're getting error. But anyway, why do you need for loop when you can just return 0 ? Actually in case when currentState equals COUNTING your method will return 0 in the first iteration.

Upvotes: 1

MByD
MByD

Reputation: 137272

You get the error as there is one case that "theoretically" you may not return anything:

if (currentState == COUNTING)
  {
    for (int i = 0; i < 99; i++)
    {
      value = i;
      return value;
    }
// right here
}

Now, it is clear to me (and you) that you will not get there, but not to the compiler.

Apart from this, the return inside the loop makes no sense, as you are going to enter it once, when i is zero, and return it, but that's another story which I can't help with because it's not clear to me what's the purpose of this function.

Upvotes: 6

talnicolas
talnicolas

Reputation: 14053

What if you enter the if but never enter the for loop? no return will be reached. You have to add a return at the end of your method that could return a failure value for example.

Upvotes: 3

Related Questions