Reputation: 3652
Ok, this must be something really stupid....my statement is returning 2:
Code:
public static void main (String [] args)
{
System.out.println(countToTen(1));
}
public static int countToTen(int last_answer){
last_answer++;
if(last_answer != 10){
countToTen(last_answer);
}
return last_answer;
}
Upvotes: 0
Views: 771
Reputation: 955
public static void main (String [] args)
{
System.out.println(countToTen(1));
}
public static int countToTen(int last_answer)
{
last_answer++;
if(last_answer != 10)
{
return countToTen(last_answer); //Here was the error
}
return last_answer;
}
Upvotes: 0
Reputation: 979
My proposal
public static int countToTen(int last_answer){
last_answer++;
if(last_answer < 10){
return countToTen(last_answer);
} else {
return last_answer;
}
}
You are not passing the argument by reference, it is a copy. You are doing a modification in last_answer in the context of method, but this change is not propagate outside, because in the end you return last_answer++
Upvotes: 0
Reputation: 17629
Try replacing your if
statement with:
if(last_answer != 10){
return countToTen(last_answer);
}
Without the return
statement, the recursive calls do get executed, but the calculated result is never returned.
The order of calls with your broken code looks like:
countToTen(1)
-> countToTen(2)
--> countToTen(3)
---> more calls to countToTen()
--- ... --> countToTen(10) // do nothing, and return to the top-level method call
-> return 2 // 2 because you incremented it using lastAnswer++
Upvotes: 4
Reputation: 679
If you want to print out 1,2,3,4 ... 10, you need to print out the answer in every phase separately
public static void main (String [] args){
countToTen(1);
}
public static void countToTen(int last_answer){
System.out.println(last_answer);
last_answer++;
if(last_answer <= 10){
countToTen(last_answer);
}
}
Upvotes: 0
Reputation: 21718
Your function returns the value from the first call. It is the initial value (1) incremented once by the ++ statement, so the function returns 2.
Integers are passed by value in Java, incrementing the passed value inside the function does not change the value outside:
int x = 0;
v(x);
// x still 0 here.
void v(int x) {
x = 100;
}
Upvotes: 2
Reputation: 2154
Try this:
public static int countToTen(int last_answer){
last_answer++;
if(last_answer != 10){
return countToTen(last_answer);
}
else {
return last_answer;
}
}
Upvotes: 0