Pregunta

Ok, this must be something really stupid....my statement is returning 2:

  • When I print out the values they are all correct
  • The return statement is wrong somehow

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;
}
¿Fue útil?

Solución

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++

Otros consejos

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;
}

Try this:

public static int countToTen(int last_answer){

  last_answer++;

  if(last_answer != 10){
    return countToTen(last_answer);
  }
  else {
    return last_answer;
  }
} 

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);
    }
} 

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++

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;
} 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top