Question:
Why am i getting this "Missing return statement" error when i do have return statement?
jackin
2013-12-10 19:36:58 UTC
public Lab09NodeClass find(int key)
{

if(isEmpty())
{
System.out.println("List is empty! CANNOT FIND!");
}
else
{
for(int c=numOfNodes; c >0; c--)
{
if(key == current.getKey())
{
System.out.println("Found node with key " + current);
break;
}
else
{
step(); //Method to step up current
}

}


}//End of else-clause
if(key!=current.getKey())
{
System.out.println("Can't find node with key " + key);

}
else
{
return current;
}

}//End of find method
Four answers:
Sam
2013-12-10 19:44:35 UTC
Because you are not placing a return in the last 'if' statement.



public Lab09NodeClass find(int key)

{



if(isEmpty())

{

System.out.println("List is empty! CANNOT FIND!");

}

else

{

for(int c=numOfNodes; c >0; c--)

{

if(key == current.getKey())

{

System.out.println("Found node with key " + current);

break;

}

else

{

step(); //Method to step up current

}



}





}//End of else-clause

if(key!=current.getKey())

{

System.out.println("Can't find node with key " + key);

return null; // <---- You forgot this....

}

else

{

return current;

}



}//End of find method







A better way to write this would be...

}//End of else-clause

if(key!=current.getKey())

System.out.println("Can't find node with key " + key);



return current;

}//End of find method
adel
2013-12-11 03:44:36 UTC
System.out.println isn't a substitute for a return statement. in your first method

public Lab09NodeClass find(int key) its expecting you to return an object of type

Lab09NodeClass
modulo_function
2013-12-11 03:42:37 UTC
The problem is that for your logical if...else structure, there is a path which will not contain the return.



The fix is easy: I recommend that you simply add a return at the end of the method. I also recommend that you return a value that is clearly a flag that something has gone wrong. I usually return -77 for a method that should never return a negative value...
Joe
2013-12-11 03:43:38 UTC
Your return is in a conditional clause (that last "else" clause).



If key!=current.getKey(), it never gets to a "return" statement.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...