public class cash
{
public void test(int a)
{
if(a<5)
{
System.out.print(a+" ");
test(++a);
System.out.println(a);
}
System.out.println("fin");
}
public static void main(String[] argsc)
{
cash c=new cash();
c.test(1);
}
}
The output:
1 2 3 4 fin
5
fin
4
fin
3
fin
2
fin
why ? I think the output should be 1 2 3 4 fin.
thank you very much.
Ok, so this is your recursive method:
every statement in this method gets invoked when you call it. lets think about the semantics in this method.
This list describes in words, what your method does:
test(++a),"fin"Your first problem is, that you always (during every invocation of
test()) print out"fin". put it in anelse {...}block to fix it.Your second problem is, that you print out the incremented value of a, thats why you get your output. remove the second println-statement (
System.out.println(a);) to fix that.The correct implementation of your method would look like this: