I am a beginner in Java... When I compile the program it says "missing return statement" though i don't understand why.... HELP
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
I am a beginner in Java... When I compile the program it says "missing return statement" though i don't understand why.... HELP
public static int fact(int n) {
Is a method that returns an Integer value.
You are returning values only if a condition holds.
If that condition doesn't hold, then the method won't return anything.
To correct this, you need to return a value which is suitable for a condition not holding.
Off-topic: Could you please always surround your code with tags, such as ones in my signature.
Last edited by newbie; February 5th, 2011 at 07:46 AM.
Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code
public static int fact(int n)
{
int factorial;
if(n>0)
{
factorial=n*fact(n-1);
return factorial;
}
else
if(n==0)
return 1;
}because in the case when both of the conditions"missing return statement"
if(n>0)
and
else
if(n==0)
will false what this function will return.
in java if you are specifying any return type then for every case it must return some value of that return type.
No.. it lies with how you're returning.
If(n<0) is a condition itself...So thats not always going to be true.
Place a return inside an else clause.
Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code
if (condition1IsTrue) { //do something } else if (condition2IsTrue) { //do something else } else { //do something if NONE of the above conditions hold} }
Currently, you're saying, if condition1 is true return x, else if condition2 is true, return y.
But what you are not stating is, what to return if NONE of those conditions are true.
The method always expects a value to be returned, and with your code only returning in conditional clauses, there is a risk that it might not always return a value.
Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code
moodycrab3 (February 6th, 2011)
I understand what you mean.... Thanks so very much...!!!
Please mark this thread as solved.