Code Java:
I am a beginner in Java... When I compile the program it says "missing return statement" though i don't understand why:confused::confused::confused:.... HELP
Printable View
Code Java:
I am a beginner in Java... When I compile the program it says "missing return statement" though i don't understand why:confused::confused::confused:.... 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.
Quote:
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 conditionsQuote:
"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.
Code java: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.
I understand what you mean.... Thanks so very much...!!!
Please mark this thread as solved.